Skip to content

Commit

Permalink
KhaiiiApi 생성자에 사전 디렉터리와 옵션을 전달할 수 있게 하여 객체 생성과 동시에 리소스 오픈을 하도록 수정 #13
Browse files Browse the repository at this point in the history
  • Loading branch information
krikit committed Dec 15, 2018
1 parent 7b7862e commit f5d93fd
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 15 deletions.
36 changes: 22 additions & 14 deletions src/main/python/khaiii/khaiii.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,15 @@
# imports #
###########
import argparse
from argparse import Namespace
import ctypes
from ctypes.util import find_library
import logging
import json
import os
import sys
import platform
import sys
from typing import List


#########
Expand Down Expand Up @@ -78,7 +81,7 @@ def __init__(self):
def __str__(self):
return '{}/{}'.format(self.lex, self.tag)

def set(self, morph: ctypes.POINTER(_khaiii_morph_t), align: list):
def set(self, morph: ctypes.POINTER(_khaiii_morph_t), align: List[List[int]]):
"""
khaiii_morph_t 구조체로부터 형태소 객체의 내용을 채운다.
Args:
Expand Down Expand Up @@ -127,7 +130,8 @@ def set(self, word: ctypes.POINTER(_khaiii_word_t), in_str: str, align: list):
self.morphs = self._make_morphs(word.contents.morphs, align)

@classmethod
def _make_morphs(cls, morph_head: ctypes.POINTER(_khaiii_morph_t), align: list):
def _make_morphs(cls, morph_head: ctypes.POINTER(_khaiii_morph_t), align: list) \
-> List[KhaiiiMorph]:
"""
어절 내에 포함된 형태소의 리스트를 생성한다.
Args:
Expand All @@ -150,10 +154,12 @@ class KhaiiiApi:
"""
khaiii API 객체
"""
def __init__(self, lib_path: str = ''):
def __init__(self, lib_path: str = '', rsc_dir: str = '', opts: dict = None):
"""
Args:
lib_path: (shared) 라이브러리의 경로
rsc_dir: 리소스 디렉토리
opts: 옵션
"""
self._handle = -1
if not lib_path:
Expand All @@ -170,32 +176,34 @@ def __init__(self, lib_path: str = ''):
self._lib = ctypes.CDLL(lib_path)
self._set_arg_res_types()
self.set_log_level('all', 'warn')
self.open(rsc_dir, opts)

def __del__(self):
self.close()

def version(self):
def version(self) -> str:
"""
khaiii_version() API
Returns:
버전 문자열
"""
return self._lib.khaiii_version().decode('UTF-8')

def open(self, rsc_dir: str = '', opt_str: str = ''):
def open(self, rsc_dir: str = '', opts: dict = None):
"""
khaiii_open() API
Args:
rsc_dir: 리소스 디렉토리
opt_str: 옵션 문자열 (JSON 포맷)
opts: 옵션
"""
self.close()
if not rsc_dir:
rsc_dir = os.path.join(os.path.dirname(__file__), 'share/khaiii')
opt_str = json.dumps(opts) if opts else ''
self._handle = self._lib.khaiii_open(rsc_dir.encode('UTF-8'), opt_str.encode('UTF-8'))
if self._handle < 0:
raise KhaiiiExcept(self._last_error())
logging.info('khaiii opened with rsc_dir: "%s", opt_str: "%s"', rsc_dir, opt_str)
logging.info('khaiii opened with rsc_dir: "%s", options: "%s"', rsc_dir, str(opts))

def close(self):
"""
Expand All @@ -206,7 +214,7 @@ def close(self):
logging.debug('khaiii closed')
self._handle = -1

def analyze(self, in_str: str, opt_str: str = ''):
def analyze(self, in_str: str, opt_str: str = '') -> List[KhaiiiWord]:
"""
khaiii_analyze() API
Args:
Expand All @@ -224,7 +232,7 @@ def analyze(self, in_str: str, opt_str: str = ''):
self._free_results(results)
return words

def analyze_bfr_errpatch(self, in_str: str, opt_str: str = ''):
def analyze_bfr_errpatch(self, in_str: str, opt_str: str = '') -> List[int]:
"""
khaiii_analyze_bfr_errpatch() dev API
Args:
Expand Down Expand Up @@ -278,7 +286,7 @@ def _free_results(self, results: ctypes.POINTER(_khaiii_word_t)):
assert self._handle >= 0
self._lib.khaiii_free_results(self._handle, results)

def _last_error(self):
def _last_error(self) -> str:
"""
khaiii_last_error() API
Returns:
Expand Down Expand Up @@ -312,7 +320,7 @@ def _set_arg_res_types(self):
self._lib.khaiii_set_log_levels.restype = ctypes.c_int

@classmethod
def _make_words(cls, in_str: str, results: ctypes.POINTER(_khaiii_word_t)):
def _make_words(cls, in_str: str, results: ctypes.POINTER(_khaiii_word_t)) -> List[KhaiiiWord]:
"""
linked-list 형태의 API 분석 결과로부터 어절(KhaiiiWord) 객체의 리스트를 생성
Args:
Expand All @@ -332,7 +340,7 @@ def _make_words(cls, in_str: str, results: ctypes.POINTER(_khaiii_word_t)):
return words

@classmethod
def _get_align(cls, in_str: str):
def _get_align(cls, in_str: str) -> List[List[int]]:
"""
byte-음절 정렬 정보를 생성. byte 길이 만큼의 각 byte 위치별 음절 위치
Args:
Expand All @@ -350,7 +358,7 @@ def _get_align(cls, in_str: str):
#############
# functions #
#############
def run(args):
def run(args: Namespace):
"""
run function which is the start point of program
Args:
Expand Down
1 change: 0 additions & 1 deletion src/test/python/test_khaiii/test_khaiii.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ class TestKhaiii(unittest.TestCase):
def setUp(self):
self._api = khaiii.KhaiiiApi()
self._api.set_log_level('all', 'warn')
self._api.open()

def tearDown(self):
self._api.close()
Expand Down

0 comments on commit f5d93fd

Please sign in to comment.