### Java API example for Kiwi tokenization, sentence splitting, and joining Source: https://github.com/bab2min/kiwi/blob/main/bindings/java/README.md Complete Java example showing how to initialize Kiwi, tokenize text, split into sentences, and join tokens. Includes commented alternative initialization using KiwiBuilder and output comments. ```java import java.util.Arrays; import kr.pe.bab2min.Kiwi; import kr.pe.bab2min.KiwiBuilder; public class KiwiExample { public static void main(String[] args) throws Exception { // Kiwi 인스턴스 생성 방법 (1) Kiwi kiwi = Kiwi.init("path_to_kiwi_model"); /* // Kiwi 인스턴스 생성 방법 (2) try(KiwiBuilder builder = new KiwiBuilder("path_to_kiwi_model")) { // 기본 옵션으로 Kiwi 인스턴스 생성 kiwi = builder.build(); // 오타 교정 기능을 사용하여 Kiwi 인스턴스 생성 kiwi = builder.build(KiwiBuilder.basicTypoSet, 2.0f); } */ // 형태소 분석 // Kiwi.Match에 대한 자세한 설명은 // https://github.com/bab2min/Kiwi/blob/c849ee06f788ca07b6c924f3497bcce89e9dfa9a/include/kiwi/PatternMatcher.h // 를 참고하세요. Kiwi.Token[] tokens = kiwi.tokenize("분석할 텍스트", Kiwi.Match.allWithNormalizing); System.out.println(Arrays.deepToString(tokens)); /* Output: [Token(form=분석, tag=NNG, position=0, length=2), Token(form=하, tag=XSV, position=2, length=1), Token(form=ᆯ, tag=ETM, position=2, length=1), Token(form=텍스트, tag=NNG, position=4, length=3)]*/ // 문장 분할 Kiwi.Sentence[] sents = kiwi.splitIntoSents("텍스트를 문장별로 분할합니다. 잘 분할됩니까?", Kiwi.Match.allWithNormalizing); System.out.println(Arrays.deepToString(sents)); /* Output: [Sentence(text=텍스트를 문장별로 분할합니다., start=0, end=16, subSents=[]), Sentence(text=잘 분할됩니까?, start=17, end=25, subSents=[])]*/ // 형태소 결합 Kiwi.JoinableToken[] joinableTokens = new Kiwi.JoinableToken[]{ new Kiwi.JoinableToken("키위", Kiwi.POSTag.nnp), new Kiwi.JoinableToken("을", Kiwi.POSTag.jko), new Kiwi.JoinableToken("사용", Kiwi.POSTag.nng), new Kiwi.JoinableToken("하", Kiwi.POSTag.xsv), new Kiwi.JoinableToken("었", Kiwi.POSTag.ep), new Kiwi.JoinableToken("다", Kiwi.POSTag.ef), }; String joined = kiwi.join(joinableTokens); System.out.println(joined); /* Output: 키위를 사용했다*/ } } ``` -------------------------------- ### Verify Kiwi installation with kiwi-evaluator Source: https://github.com/bab2min/kiwi/blob/main/README.md Runs the kiwi-evaluator on the provided eval data to check the installation. The output shows loading time, architecture type, model size, memory usage, and per-file scores. ```console $ ./kiwi-evaluator --model ../models/base ../eval_data/* --largest Loading Time : 981.745 ms ArchType : avx2 LM Size : 34.1853 MB Mem Usage : 278.129 MB Test file: eval_data/web.txt 0.862114, 0.852863 Total (158 lines) Time : 301.702 ms Time per Line : 1.9095 ms ================ Test file: eval_data/written.txt 0.942892, 0.943506 Total (33 lines) Time : 62.3999 ms Time per Line : 1.89091 ms ================ Test file: eval_data/web_with_typos.txt 0.754417, 0.720886 Total (97 lines) Time : 99.7661 ms Time per Line : 1.02852 ms ================ ================ Avg Score 0.853141, 0.839085 ================ ``` -------------------------------- ### Configure analysis options with MatchOptions Source: https://github.com/bab2min/kiwi/blob/main/bindings/swift/README.md Demonstrates tokenizing with default options, all options with normalization, and custom combinations of MatchOptions like .url, .email, and .normalizeCoda. ```swift // 기본 옵션으로 분석 let tokens1 = try kiwi.tokenize("www.example.com", options: .all) // URL, 이메일 등 패턴 매칭 + 정규화 let tokens2 = try kiwi.tokenize("www.example.com", options: .allWithNormalizing) // 개별 옵션 조합 let customOptions: MatchOptions = [.url, .email, .normalizeCoda] let tokens3 = try kiwi.tokenize("test@test.com", options: customOptions) ``` -------------------------------- ### Download and run KiwiJava JAR from command line Source: https://github.com/bab2min/kiwi/blob/main/bindings/java/README.md Commands to download the model and JAR, extract the model, and run the JAR with the model path. The output shows the loaded Kiwi version and tokenization of '안녕하세요?'. ```bash # Linux x86-64 환경을 가정 # 모델 파일 다운로드 $ wget https://github.com/bab2min/Kiwi/releases/download/v0.19.0/kiwi_model_v0.19.0_base.tgz $ tar -zxvf kiwi_model_v0.19.0_base.tgz # 압축 해제. 모델을 포함한 models/base라는 폴더가 생성됨 # KiwiJava 다운로드 $ wget https://github.com/bab2min/Kiwi/releases/download/v0.19.0/kiwi-java-v0.19.0-lnx-x86-64.jar # 모델 파일은 Patch가 다르더라도 Major, Minor 버전이 동일하면 호환됩니다. # 즉, kiwi_model_v0.19.0은 kiwi-java-v0.19.* 전부에서 사용가능합니다. # jar 구동. 구동 인자로 모델 경로를 입력해주어야 함 $ java -jar kiwi-java-v0.19.0-lnx-x86-64.jar models/base/ Kiwi 0.19.0 is loaded! >> 안녕하세요? [Token(form=안녕, tag=NNG, position=0, length=2), Token(form=하, tag=XSA, position=2, length=1), Token(form=세요, tag=EF, position=3, length=2), Token(form=?, tag=SF, position=5, length=1)] ``` -------------------------------- ### Package.swift에 Kiwi 의존성 추가 Source: https://github.com/bab2min/kiwi/blob/main/bindings/swift/README.md Swift Package Manager를 통해 Kiwi를 의존성으로 추가하는 방법. Package.swift 파일에 이 코드를 추가하고, 버전은 0.24.1 이상을 지정합니다. ```swift // Package.swift dependencies: [ .package(url: "https://github.com/bab2min/Kiwi.git", from: "0.24.1") ], targets: [ .target( name: "YourApp", dependencies: ["Kiwi"] ) ] ``` -------------------------------- ### Build Kiwi from source on Linux Source: https://github.com/bab2min/kiwi/blob/main/README.md Clone the repository, pull Git LFS files, initialize submodules, and build with cmake (>=3.12) and make. Requires a C++17 compatible compiler (gcc >= 7 or similar). ```console $ git clone https://github.com/bab2min/Kiwi $ cd Kiwi $ git lfs pull $ git submodule sync $ git submodule update --init --recursive $ mkdir build && cd build $ cmake -DCMAKE_BUILD_TYPE=Release ../ $ make $ make install $ ldconfig ``` -------------------------------- ### KiwiBuilder.build(typoTransformer:typoCostThreshold:) Source: https://github.com/bab2min/kiwi/blob/main/bindings/swift/README.md Builds a Kiwi instance from the builder. This is the final step before performing analysis. ```APIDOC ## KiwiBuilder.build(typoTransformer:typoCostThreshold:) ### Description Builds a Kiwi instance from the builder. This is the final step before performing analysis. ### Method Instance Method ### Signature `build(typoTransformer:typoCostThreshold:)` ### Parameters - **typoTransformer** (TypoTransformer?) - Optional - A transformer for typo correction. - **typoCostThreshold** (Float) - Optional - Threshold for typo correction cost. ### Returns - **Kiwi** - A configured Kiwi instance. ### Example ```swift let kiwi = builder.build() ``` ``` -------------------------------- ### Kotlin에서 Kiwi 사용 예제 Source: https://github.com/bab2min/kiwi/blob/main/bindings/java/README.md KiwiBuilder.StreamProvider를 사용하여 assets 내의 kiwi_model/ 폴더에서 모델 파일을 열고, Kiwi를 빌드한 후 tokenize()로 문장을 분석합니다. 출력 예시가 주석으로 포함되어 있습니다. ```kotlin package example import android.os.Bundle import android.util.Log import androidx.activity.ComponentActivity import kr.pe.bab2min.Kiwi import kr.pe.bab2min.KiwiBuilder class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) try { // 모델 파일을 assets 내의 kiwi_model/ 폴더에 넣었다고 가정 val streamProvider = KiwiBuilder.StreamProvider { filename -> try { // assets 내의 kiwi_model/ 폴더 내의 파일을 연다. assets.open("kiwi_model/$filename") } catch (e: Exception) { null // 파일이 없으면 null 반환 } } val kiwi = KiwiBuilder(streamProvider).build() val res = kiwi.tokenize("안드로이드에서도 Kiwi를!", Kiwi.Match.allWithNormalizing) for (token in res) { Log.d("Kiwi", "${token.form} / ${Kiwi.POSTag.toString(token.tag)}") } /* 다음과 같이 출력됨 안드로이드 / NNG 에서 / JKB 도 / JX Kiwi / SL 를 / JKO ! / SF */ } catch (e: Exception) { Log.e("Kiwi", "Error", e) } } } ``` -------------------------------- ### Gradle에 AAR 파일 추가하기 Source: https://github.com/bab2min/kiwi/blob/main/bindings/java/README.md 다운로드한 kiwi-android-VERSION.aar 파일을 app/libs/ 폴더에 복사한 후, app/build.gradle의 dependencies 블록에 implementation files('libs/kiwi-android-VERSION.aar')를 추가합니다. ```gradle android { ... } dependencies { implementation files('libs/kiwi-android-VERSION.aar') ... } ``` -------------------------------- ### KiwiBuilder.build(typoTransformer:typoCostThreshold:) Source: https://github.com/bab2min/kiwi/blob/main/bindings/swift/README.md Builds a Kiwi instance with a typo transformer and a cost threshold for typo correction. ```APIDOC ## KiwiBuilder.build(typoTransformer:typoCostThreshold:) ### Description Builds a Kiwi instance with a typo transformer and a cost threshold for typo correction. ### Method build ### Parameters - **typoTransformer** (TypoTransformer) - Required - The transformer to use for typo correction. - **typoCostThreshold** (Double) - Required - The maximum cost for a typo correction to be applied. ### Request Example ```swift let kiwi = try builder.build( typoTransformer: typoTransformer, typoCostThreshold: 2.5 ) ``` ### Response Returns a Kiwi instance. Throws on error. ``` -------------------------------- ### 기본 형태소 분석 예제 Source: https://github.com/bab2min/kiwi/blob/main/bindings/swift/README.md KiwiBuilder를 사용하여 번들에서 모델을 로드하고 Kiwi 인스턴스를 빌드한 후, tokenize 메서드로 형태소 분석을 수행합니다. 출력 예시가 포함되어 있습니다. ```swift import Kiwi do { // 1. KiwiBuilder 생성 (번들에서 모델 로드) let builder = try KiwiBuilder( bundle: .main, modelDirectory: "KiwiModels" ) // 2. Kiwi 인스턴스 빌드 let kiwi = try builder.build() // 3. 형태소 분석 let tokens = try kiwi.tokenize("안녕하세요, 키위 형태소 분석기입니다!") for token in tokens { print("\(token.form)/\(token.tag.description)") } // 출력: // 안녕/NNG // 하/XSA // 시/EP // 어요/EF // ,/SP // 키위/NNG // 형태소/NNG // 분석기/NNG // 이/VCP // ㅂ니다/EF // !/SF } catch { print("오류: \(error)") } ``` -------------------------------- ### KiwiBuilder.init(bundle:modelDirectory:numThreads:options:enabledDialects:) Source: https://github.com/bab2min/kiwi/blob/main/bindings/swift/README.md Initializes a KiwiBuilder using a bundle and model directory. This is useful for loading models bundled with the application. ```APIDOC ## KiwiBuilder.init(bundle:modelDirectory:numThreads:options:enabledDialects:) ### Description Initializes a KiwiBuilder using a bundle and model directory. This is useful for loading models bundled with the application. ### Method Initializer ### Signature `init(bundle:modelDirectory:numThreads:options:enabledDialects:)` ### Parameters - **bundle** (Bundle) - Required - The bundle containing the model. - **modelDirectory** (String) - Optional - Directory within the bundle where the model resides. - **numThreads** (Int) - Optional - Number of threads to use. - **options** (KiwiBuilderOptions) - Optional - Builder options. - **enabledDialects** (Set) - Optional - Set of enabled dialects. ### Throws - `KiwiError.modelNotFound` if the model file is not found. - `KiwiError.operationFailed` if initialization fails. - `KiwiError.invalidHandle` if an invalid handle is encountered. ### Example ```swift do { let builder = try KiwiBuilder(bundle: .main, modelDirectory: "Models") } catch { print("Error: \(error)") } ``` ``` -------------------------------- ### 모델 폴더 구조 예시 Source: https://github.com/bab2min/kiwi/blob/main/bindings/swift/README.md iOS/macOS 앱에서 모델을 번들링할 때 필요한 폴더 구조를 보여줍니다. 'KiwiModels' 폴더에 combiningRule.txt, default.dict, extract.mdl 등의 모델 파일이 포함되어야 합니다. ```text YourApp/ ├── Resources/ │ └── KiwiModels/ ← 모델 폴더 │ ├── combiningRule.txt │ ├── default.dict │ ├── extract.mdl │ └── ... ``` -------------------------------- ### Add user dictionary words and load dictionary file Source: https://github.com/bab2min/kiwi/blob/main/bindings/swift/README.md Shows how to add individual words with tags and scores, and load a tab-separated dictionary file (word\ttag\tscore) using KiwiBuilder. ```swift let builder = try KiwiBuilder(bundle: .main, modelDirectory: "KiwiModels") // 단어 직접 추가 try builder.addWord("키위피", tag: .nnp, score: 0.0) // 고유명사로 추가 try builder.addWord("딥러닝", tag: .nng, score: 0.0) // 일반명사로 추가 // 사전 파일 로드 (탭으로 구분된 형식: 단어\t품사\t점수) try builder.loadDict("/path/to/user_dict.txt") let kiwi = try builder.build() ``` -------------------------------- ### Create TypoTransformer variants Source: https://github.com/bab2min/kiwi/blob/main/bindings/swift/README.md Shows how to create empty, basic, and default typo transformers with different typo sets. ```swift // 빈 트랜스포머 let empty = try TypoTransformer() // 기본 오타 세트 let basic = try TypoTransformer.basic() // 다양한 오타 세트 let continual = try TypoTransformer.default(.continualTypoSet) let withLengthening = try TypoTransformer.default(.basicTypoSetWithContinualAndLengthening) ``` -------------------------------- ### 다중 분석 결과 얻기 Source: https://github.com/bab2min/kiwi/blob/main/bindings/swift/README.md analyze 메서드에 topN 매개변수를 사용하여 여러 개의 분석 후보를 얻는 방법. 각 후보는 점수와 토큰 목록을 포함합니다. ```swift // topN 개의 분석 후보 반환 let results = try kiwi.analyze("감기는 감기다", topN: 3) for (index, result) in results.enumerated() { print("후보 \(index + 1) (점수: \(result.score)):") for token in result.tokens { print(" \(token.form)/\(token.tag.description)") } } ``` -------------------------------- ### KiwiBuilder.init(modelPath:numThreads:options:enabledDialects:) Source: https://github.com/bab2min/kiwi/blob/main/bindings/swift/README.md Initializes a KiwiBuilder with a model path. This is the primary way to create a builder for loading a Kiwi model from a file path. ```APIDOC ## KiwiBuilder.init(modelPath:numThreads:options:enabledDialects:) ### Description Initializes a KiwiBuilder with a model path. This is the primary way to create a builder for loading a Kiwi model from a file path. ### Method Initializer ### Signature `init(modelPath:numThreads:options:enabledDialects:)` ### Parameters - **modelPath** (String) - Required - Path to the model file. - **numThreads** (Int) - Optional - Number of threads to use. - **options** (KiwiBuilderOptions) - Optional - Builder options. - **enabledDialects** (Set) - Optional - Set of enabled dialects. ### Throws - `KiwiError.modelNotFound` if the model file is not found. - `KiwiError.operationFailed` if initialization fails. - `KiwiError.invalidHandle` if an invalid handle is encountered. ### Example ```swift do { let builder = try KiwiBuilder(modelPath: "/path/to/model") } catch { print("Error: \(error)") } ``` ``` -------------------------------- ### 경로로 모델 로드 Source: https://github.com/bab2min/kiwi/blob/main/bindings/swift/README.md 모델 파일의 직접 경로를 지정하여 KiwiBuilder를 생성하는 방법. numThreads 매개변수로 스레드 수를 지정할 수 있으며, -1은 자동 설정입니다. ```swift // 직접 경로 지정 let builder = try KiwiBuilder( modelPath: "/path/to/models", numThreads: 4 // 스레드 수 지정 (-1: 자동) ) ``` -------------------------------- ### KiwiBuilder.loadDict(_:) Source: https://github.com/bab2min/kiwi/blob/main/bindings/swift/README.md Loads a user dictionary from a file. The file format is tab-separated: word, part-of-speech tag, and score. ```APIDOC ## KiwiBuilder.loadDict(_:) ### Description Loads a user dictionary from a file. The file format is tab-separated: word, part-of-speech tag, and score. ### Method loadDict ### Parameters - **path** (String) - Required - The file path to the dictionary file. ### Request Example ```swift try builder.loadDict("/path/to/user_dict.txt") ``` ### Response No return value. Throws on error. ``` -------------------------------- ### Enable dialects in KiwiBuilder Source: https://github.com/bab2min/kiwi/blob/main/bindings/swift/README.md Shows how to enable specific dialects (standard, gyeongsang, jeolla) when building the Kiwi instance. ```swift let builder = try KiwiBuilder( bundle: .main, modelDirectory: "KiwiModels", enabledDialects: [.standard, .gyeongsang, .jeolla] ) let kiwi = try builder.build() ``` -------------------------------- ### 소스에서 AAR 빌드하기 Source: https://github.com/bab2min/kiwi/blob/main/bindings/java/README.md bindings/java 디렉토리에서 ./gradlew assembleRelease를 실행하여 AAR 파일을 빌드합니다. 결과물은 build/outputs/aar/ 디렉토리에 생성됩니다. ```bash cd bindings/java ./gradlew assembleRelease ``` -------------------------------- ### KiwiBuilder(bundle:modelDirectory:enabledDialects:) Source: https://github.com/bab2min/kiwi/blob/main/bindings/swift/README.md Initializes a KiwiBuilder with a set of enabled dialects. This allows the tokenizer to recognize dialect-specific variations. ```APIDOC ## KiwiBuilder(bundle:modelDirectory:enabledDialects:) ### Description Initializes a KiwiBuilder with a set of enabled dialects. This allows the tokenizer to recognize dialect-specific variations. ### Method init ### Parameters - **bundle** (Bundle) - Required - The bundle containing the model files. - **modelDirectory** (String) - Required - The directory name where the Kiwi models are located. - **enabledDialects** ([Dialect]) - Required - An array of dialects to enable. ### Request Example ```swift let builder = try KiwiBuilder( bundle: .main, modelDirectory: "KiwiModels", enabledDialects: [.standard, .gyeongsang, .jeolla] ) ``` ### Response Returns a KiwiBuilder instance. Throws on error. ### Dialect Options - `.standard` - Standard language (default) - `.gyeonggi` - Gyeonggi dialect - `.chungcheong` - Chungcheong dialect - `.gangwon` - Gangwon dialect - `.gyeongsang` - Gyeongsang dialect - `.jeolla` - Jeolla dialect - `.jeju` - Jeju dialect - `.hwanghae` - Hwanghae dialect - `.hamgyeong` - Hamgyeong dialect - `.pyeongan` - Pyeongan dialect - `.archaic` - Archaic language ``` -------------------------------- ### Kiwi.version (static) Source: https://github.com/bab2min/kiwi/blob/main/bindings/swift/README.md Returns the version string of the Kiwi library. ```APIDOC ## Kiwi.version (static) ### Description Returns the version string of the Kiwi library. ### Property Static Property ### Type String ### Example ```swift print(Kiwi.version) ``` ``` -------------------------------- ### TypoTransformer() and TypoTransformer.default(_:) Source: https://github.com/bab2min/kiwi/blob/main/bindings/swift/README.md Creates a TypoTransformer with no typos or with a predefined typo set. ```APIDOC ## TypoTransformer() and TypoTransformer.default(_:) ### Description Creates a TypoTransformer with no typos or with a predefined typo set. ### Method init / default ### Parameters - **typoSet** (TypoSet) - Optional - The typo set to use. Available sets: `.continualTypoSet`, `.basicTypoSetWithContinualAndLengthening`. ### Request Example ```swift let empty = try TypoTransformer() let continual = try TypoTransformer.default(.continualTypoSet) let withLengthening = try TypoTransformer.default(.basicTypoSetWithContinualAndLengthening) ``` ### Response Returns a TypoTransformer instance. Throws on error. ``` -------------------------------- ### Kiwi.tokenize(_:options:) Source: https://github.com/bab2min/kiwi/blob/main/bindings/swift/README.md Tokenizes the input text using the specified match options. Options control pattern recognition (URL, email, etc.) and normalization. ```APIDOC ## Kiwi.tokenize(_:options:) ### Description Tokenizes the input text using the specified match options. Options control pattern recognition (URL, email, etc.) and normalization. ### Method tokenize ### Parameters - **text** (String) - Required - The text to tokenize. - **options** (MatchOptions) - Required - Options for pattern matching and normalization. Can be a single option or a combination. ### Request Example ```swift let tokens1 = try kiwi.tokenize("www.example.com", options: .all) let tokens2 = try kiwi.tokenize("www.example.com", options: .allWithNormalizing) let customOptions: MatchOptions = [.url, .email, .normalizeCoda] let tokens3 = try kiwi.tokenize("test@test.com", options: customOptions) ``` ### Response Returns an array of Token objects. Throws on error. ### MatchOptions - `.url` - URL pattern recognition - `.email` - Email pattern recognition - `.hashtag` - Hashtag recognition - `.mention` - Mention (@) recognition - `.serial` - Serial number recognition - `.normalizeCoda` - Coda normalization (e.g., 잇다 → 있다) - `.joinNounPrefix` - Noun prefix joining - `.joinNounSuffix` - Noun suffix joining - `.joinVerbSuffix` - Verb suffix joining - `.joinAdjSuffix` - Adjective suffix joining - `.splitComplex` - Split complex morphemes - `.all` - All basic options - `.allWithNormalizing` - All options plus normalization ``` -------------------------------- ### 문장 분리 예제 Source: https://github.com/bab2min/kiwi/blob/main/bindings/swift/README.md splitIntoSentences 메서드를 사용하여 텍스트를 문장 단위로 분리하는 방법. 각 문장의 텍스트, 시작 위치, 길이를 출력합니다. 출력 예시가 포함되어 있습니다. ```swift let text = "안녕하세요. 키위입니다. 형태소 분석을 합니다." let sentences = try kiwi.splitIntoSentences(text) for sentence in sentences { print("문장: \(sentence.text)") print(" 시작: \(sentence.start), 길이: \(sentence.length)") } // 출력: // 문장: 안녕하세요. // 시작: 0, 길이: 18 // 문장: 키위입니다. // 시작: 19, 길이: 16 // 문장: 형태소 분석을 합니다. // 시작: 36, 길이: 28 ``` -------------------------------- ### Use basic typo transformer Source: https://github.com/bab2min/kiwi/blob/main/bindings/swift/README.md Creates a basic typo transformer and builds the Kiwi instance with a typo cost threshold, then tokenizes a sentence with automatic typo correction. ```swift // 기본 오타 교정기 사용 let typoTransformer = try TypoTransformer.basic() let kiwi = try builder.build( typoTransformer: typoTransformer, typoCostThreshold: 2.5 ) let tokens = try kiwi.tokenize("장례희망이 뭐야?") // 오타 자동 교정 ``` -------------------------------- ### KiwiBuilder.loadDict(_:) Source: https://github.com/bab2min/kiwi/blob/main/bindings/swift/README.md Loads a dictionary file into the builder. This can be used to load additional user dictionaries. ```APIDOC ## KiwiBuilder.loadDict(_:) ### Description Loads a dictionary file into the builder. This can be used to load additional user dictionaries. ### Method Instance Method ### Signature `loadDict(_:)` ### Parameters - **path** (String) - Required - Path to the dictionary file. ### Example ```swift builder.loadDict("/path/to/dict.txt") ``` ``` -------------------------------- ### Define WebAssembly executable target Source: https://github.com/bab2min/kiwi/blob/main/bindings/wasm/CMakeLists.txt Creates an executable target named ${PROJECT_NAME}-wasm from kiwi_wasm.cpp. ```cmake add_executable( "${PROJECT_NAME}-wasm" kiwi_wasm.cpp ) ``` -------------------------------- ### Link static library to WebAssembly target Source: https://github.com/bab2min/kiwi/blob/main/bindings/wasm/CMakeLists.txt Links the WebAssembly executable against the static library target ${PROJECT_NAME}_static. ```cmake target_link_libraries( "${PROJECT_NAME}-wasm" "${PROJECT_NAME}_static" ) ``` -------------------------------- ### Kiwi.createJoiner() Source: https://github.com/bab2min/kiwi/blob/main/bindings/swift/README.md Creates a Joiner for combining morphemes into natural sentences. ```APIDOC ## Kiwi.createJoiner() ### Description Creates a Joiner for combining morphemes into natural sentences. ### Method createJoiner ### Parameters None. ### Request Example ```swift let joiner = try kiwi.createJoiner() ``` ### Response Returns a Joiner instance. Throws on error. ``` -------------------------------- ### TypoTransformer.basic() Source: https://github.com/bab2min/kiwi/blob/main/bindings/swift/README.md Creates a basic typo transformer for automatic typo correction during tokenization. ```APIDOC ## TypoTransformer.basic() ### Description Creates a basic typo transformer for automatic typo correction during tokenization. ### Method basic ### Parameters None. ### Request Example ```swift let typoTransformer = try TypoTransformer.basic() ``` ### Response Returns a TypoTransformer instance. Throws on error. ``` -------------------------------- ### Joiner.join() Source: https://github.com/bab2min/kiwi/blob/main/bindings/swift/README.md Returns the combined text from the added morphemes. ```APIDOC ## Joiner.join() ### Description Returns the combined text from the added morphemes. ### Method Instance Method ### Signature `join()` ### Returns - **String** - The joined text. ### Example ```swift let text = joiner.join() ``` ``` -------------------------------- ### Kiwi.createJoiner(useLMSearch:) Source: https://github.com/bab2min/kiwi/blob/main/bindings/swift/README.md Creates a Joiner instance for combining morphemes back into text. This is useful for restoring original text from tokens. ```APIDOC ## Kiwi.createJoiner(useLMSearch:) ### Description Creates a Joiner instance for combining morphemes back into text. This is useful for restoring original text from tokens. ### Method Instance Method ### Signature `createJoiner(useLMSearch:)` ### Parameters - **useLMSearch** (Bool) - Optional - Whether to use language model search during joining. ### Returns - **Joiner** - A new Joiner instance. ### Example ```swift let joiner = kiwi.createJoiner() ``` ``` -------------------------------- ### Kiwi.tokenize(_:options:) Source: https://github.com/bab2min/kiwi/blob/main/bindings/swift/README.md Performs morphological analysis and returns only the top result. This is a convenience method for typical use cases. ```APIDOC ## Kiwi.tokenize(_:options:) ### Description Performs morphological analysis and returns only the top result. This is a convenience method for typical use cases. ### Method Instance Method ### Signature `tokenize(_:options:)` ### Parameters - **text** (String) - Required - The input text to analyze. - **options** (KiwiAnalyzeOptions) - Optional - Analysis options. ### Returns - **[Token]** - An array of tokens representing the top analysis. ### Example ```swift let tokens = kiwi.tokenize("안녕하세요") ``` ``` -------------------------------- ### Kiwi.analyze(_:topN:options:) Source: https://github.com/bab2min/kiwi/blob/main/bindings/swift/README.md Performs morphological analysis and returns multiple candidate results. This is useful when you need ranked analysis results. ```APIDOC ## Kiwi.analyze(_:topN:options:) ### Description Performs morphological analysis and returns multiple candidate results. This is useful when you need ranked analysis results. ### Method Instance Method ### Signature `analyze(_:topN:options:)` ### Parameters - **text** (String) - Required - The input text to analyze. - **topN** (Int) - Optional - Number of top results to return. - **options** (KiwiAnalyzeOptions) - Optional - Analysis options. ### Returns - **[[Token]]** - An array of token sequences, each representing a candidate analysis. ### Example ```swift let results = kiwi.analyze("안녕하세요", topN: 3) ``` ``` -------------------------------- ### Kiwi.createMorphemeSet() Source: https://github.com/bab2min/kiwi/blob/main/bindings/swift/README.md Creates a MorphemeSet for managing morphemes, intended for use as a blocklist in future analysis. ```APIDOC ## Kiwi.createMorphemeSet() ### Description Creates a MorphemeSet for managing morphemes, intended for use as a blocklist in future analysis. ### Method createMorphemeSet ### Parameters None. ### Request Example ```swift let morphset = try kiwi.createMorphemeSet() ``` ### Response Returns a MorphemeSet instance. Throws on error. ``` -------------------------------- ### Kiwi.splitIntoSentences(_:options:) Source: https://github.com/bab2min/kiwi/blob/main/bindings/swift/README.md Splits the input text into sentences. This is useful for preprocessing before analysis. ```APIDOC ## Kiwi.splitIntoSentences(_:options:) ### Description Splits the input text into sentences. This is useful for preprocessing before analysis. ### Method Instance Method ### Signature `splitIntoSentences(_:options:)` ### Parameters - **text** (String) - Required - The input text to split. - **options** (KiwiSplitOptions) - Optional - Splitting options. ### Returns - **[String]** - An array of sentences. ### Example ```swift let sentences = kiwi.splitIntoSentences("첫 번째 문장. 두 번째 문장.") ``` ``` -------------------------------- ### Access token information Source: https://github.com/bab2min/kiwi/blob/main/bindings/swift/README.md Iterates over tokens and prints detailed information including form, tag, position, length, word position, sentence position, score, and typo cost. ```swift let tokens = try kiwi.tokenize("서울에서 부산까지") for token in tokens { print(""" 형태: \(token.form) 품사: \(token.tag.description) 위치: \(token.position) (길이: \(token.length)) 어절 번호: \(token.wordPosition) 문장 번호: \(token.sentencePosition) 점수: \(token.score) 오타 비용: \(token.typoCost) """) } ``` -------------------------------- ### Joiner.add(form:tag:) Source: https://github.com/bab2min/kiwi/blob/main/bindings/swift/README.md Adds a morpheme to the joiner with its part-of-speech tag. ```APIDOC ## Joiner.add(form:tag:) ### Description Adds a morpheme to the joiner with its part-of-speech tag. ### Method add ### Parameters - **form** (String) - Required - The surface form of the morpheme. - **tag** (Tag) - Required - The part-of-speech tag (e.g., .vv for verb stem, .ep for pre-final ending, .ef for final ending). ### Request Example ```swift try joiner.add(form: "먹", tag: .vv) try joiner.add(form: "었", tag: .ep) try joiner.add(form: "다", tag: .ef) ``` ### Response No return value. Throws on error. ``` -------------------------------- ### Error handling with KiwiError Source: https://github.com/bab2min/kiwi/blob/main/bindings/swift/README.md Shows how to catch KiwiError cases when initializing KiwiBuilder with an invalid model path. The catch blocks handle modelNotFound, operationFailed, invalidHandle, and a generic fallback. ```swift do { let builder = try KiwiBuilder(modelPath: "/invalid/path") } catch KiwiError.modelNotFound(let path) { print("모델을 찾을 수 없습니다: \(path)") } catch KiwiError.operationFailed(let message) { print("작업 실패: \(message)") } catch KiwiError.invalidHandle { print("잘못된 핸들") } catch { print("알 수 없는 오류: \(error)") } ``` -------------------------------- ### Error Handling Source: https://github.com/bab2min/kiwi/blob/main/bindings/swift/README.md Error types thrown by Kiwi operations and how to handle them. ```APIDOC ## Error Handling ### Description Error types thrown by Kiwi operations and how to handle them. ### Error Types - **KiwiError.modelNotFound** - Thrown when the model file is not found. - **KiwiError.operationFailed** - Thrown when an operation fails. - **KiwiError.invalidHandle** - Thrown when an invalid handle is used. ### Example ```swift do { let builder = try KiwiBuilder(modelPath: "/invalid/path") } catch KiwiError.modelNotFound(let path) { print("Model not found: \(path)") } catch KiwiError.operationFailed(let message) { print("Operation failed: \(message)") } catch KiwiError.invalidHandle { print("Invalid handle") } catch { print("Unknown error: \(error)") } ``` ``` -------------------------------- ### JSON Serialization of Token, TokenResult, Sentence Source: https://github.com/bab2min/kiwi/blob/main/bindings/swift/README.md Token, TokenResult, and Sentence conform to Codable, allowing direct JSON encoding. ```APIDOC ## JSON Serialization of Token, TokenResult, Sentence ### Description Token, TokenResult, and Sentence conform to Codable, allowing direct JSON encoding. ### Method JSONEncoder.encode ### Parameters - **value** (Codable) - Required - The object to encode (e.g., [Token]). ### Request Example ```swift let tokens = try kiwi.tokenize("안녕하세요") let encoder = JSONEncoder() encoder.outputFormatting = .prettyPrinted let jsonData = try encoder.encode(tokens) let jsonString = String(data: jsonData, encoding: .utf8)! print(jsonString) ``` ### Response Returns JSON data representing the encoded object. Throws on error. ``` -------------------------------- ### Join morphemes to form a sentence Source: https://github.com/bab2min/kiwi/blob/main/bindings/swift/README.md Creates a joiner, adds morphemes (verb stem, pre-final ending, final ending), and joins them to produce a natural sentence like '먹었다'. ```swift let joiner = try kiwi.createJoiner() try joiner.add(form: "먹", tag: .vv) // 동사 어간 try joiner.add(form: "었", tag: .ep) // 선어말 어미 try joiner.add(form: "다", tag: .ef) // 종결 어미 let text = try joiner.join() print(text) // "먹었다" ``` -------------------------------- ### KiwiBuilder.addWord(_:tag:score:) Source: https://github.com/bab2min/kiwi/blob/main/bindings/swift/README.md Adds a user-defined word to the builder's dictionary. This allows custom vocabulary to be included during analysis. ```APIDOC ## KiwiBuilder.addWord(_:tag:score:) ### Description Adds a user-defined word to the builder's dictionary. This allows custom vocabulary to be included during analysis. ### Method Instance Method ### Signature `addWord(_:tag:score:)` ### Parameters - **word** (String) - Required - The word to add. - **tag** (POSTag) - Required - The part-of-speech tag for the word. - **score** (Float) - Optional - The language model score for the word. ### Example ```swift builder.addWord("Kiwi", tag: .nnp, score: 10.0) ``` ``` -------------------------------- ### Kiwi.createMorphemeSet() Source: https://github.com/bab2min/kiwi/blob/main/bindings/swift/README.md Creates a MorphemeSet instance. This can be used to manage a set of morphemes. ```APIDOC ## Kiwi.createMorphemeSet() ### Description Creates a MorphemeSet instance. This can be used to manage a set of morphemes. ### Method Instance Method ### Signature `createMorphemeSet()` ### Returns - **MorphemeSet** - A new MorphemeSet instance. ### Example ```swift let morphemeSet = kiwi.createMorphemeSet() ``` ``` -------------------------------- ### Joiner.join() Source: https://github.com/bab2min/kiwi/blob/main/bindings/swift/README.md Joins the added morphemes into a single string, applying irregular conjugation rules automatically. ```APIDOC ## Joiner.join() ### Description Joins the added morphemes into a single string, applying irregular conjugation rules automatically. ### Method join ### Parameters None. ### Request Example ```swift let text = try joiner.join() print(text) // "먹었다" or "들어" ``` ### Response Returns a String containing the joined text. Throws on error. ``` -------------------------------- ### Verify typo correction feature with kiwi-evaluator Source: https://github.com/bab2min/kiwi/blob/main/README.md Runs kiwi-evaluator with the --typo 6 flag to test the typo correction feature added in version 0.13.0. The output shows loading time, architecture type, model size, memory usage, and per-file scores. ```console $ ./kiwi-evaluator --model ../models/base ../eval_data/* --largest --typo 6 Loading Time : 9414.45 ms ArchType : avx2 LM Size : 34.1853 MB Mem Usage : 693.945 MB Test file: eval_data/web.txt 0.86321, 0.85566 Total (158 lines) Time : 432.236 ms Time per Line : 2.73567 ms ================ Test file: eval_data/written.txt 0.941712, 0.942217 Total (33 lines) Time : 95.3079 ms Time per Line : 2.88812 ms ================ Test file: eval_data/web_with_typos.txt 0.869582, 0.865393 Total (97 lines) Time : 169.416 ms Time per Line : 1.74656 ms ================ ================ Avg Score 0.891501, 0.887757 ================ ``` -------------------------------- ### Set Emscripten linker flags for WebAssembly Source: https://github.com/bab2min/kiwi/blob/main/bindings/wasm/CMakeLists.txt Configures linker flags for the WebAssembly target: enables WASM, memory growth, ES6 module export, modularization, and file system support. ```cmake set_target_properties("${PROJECT_NAME}-wasm" PROPERTIES LINK_FLAGS "--bind -s WASM=1 -s ALLOW_MEMORY_GROWTH=1 -s EXPORT_ES6=1 -s MODULARIZE=1 -s EXPORT_NAME=kiwi -s DYNAMIC_EXECUTION=0 -s STACK_SIZE=256KB -s 'EXPORTED_RUNTIME_METHODS=[\"FS\"]'" ) ``` -------------------------------- ### Joiner.add(form:tag:autoDetectIrregular:) Source: https://github.com/bab2min/kiwi/blob/main/bindings/swift/README.md Adds a morpheme to the joiner. This is used to build text from morphemes. ```APIDOC ## Joiner.add(form:tag:autoDetectIrregular:) ### Description Adds a morpheme to the joiner. This is used to build text from morphemes. ### Method Instance Method ### Signature `add(form:tag:autoDetectIrregular:)` ### Parameters - **form** (String) - Required - The morpheme form. - **tag** (POSTag) - Required - The part-of-speech tag. - **autoDetectIrregular** (Bool) - Optional - Whether to auto-detect irregular conjugation. ### Example ```swift joiner.add(form: "안녕", tag: .nng) ``` ``` -------------------------------- ### Add morphemes to a blacklist Source: https://github.com/bab2min/kiwi/blob/main/bindings/swift/README.md Creates a morpheme set and adds a specific morpheme (주격조사 '가') to be excluded from analysis. Note that using it as a blocklist is planned for future support. ```swift let morphset = try kiwi.createMorphemeSet() try morphset.add(form: "가", tag: .jks) // 주격조사 '가' 제외 // analyze 시 blocklist로 사용 (향후 지원 예정) ``` -------------------------------- ### KiwiBuilder.addWord(_:tag:score:) Source: https://github.com/bab2min/kiwi/blob/main/bindings/swift/README.md Adds a custom word to the user dictionary with a specified part-of-speech tag and score. This allows the tokenizer to recognize user-defined terms. ```APIDOC ## KiwiBuilder.addWord(_:tag:score:) ### Description Adds a custom word to the user dictionary with a specified part-of-speech tag and score. This allows the tokenizer to recognize user-defined terms. ### Method addWord ### Parameters - **form** (String) - Required - The word to add. - **tag** (Tag) - Required - The part-of-speech tag (e.g., .nnp for proper noun, .nng for common noun). - **score** (Double) - Required - The score for the word (0.0 is typical). ### Request Example ```swift let builder = try KiwiBuilder(bundle: .main, modelDirectory: "KiwiModels") try builder.addWord("키위피", tag: .nnp, score: 0.0) try builder.addWord("딥러닝", tag: .nng, score: 0.0) ``` ### Response No return value. Throws on error. ```