Update 1/model.py
This commit is contained in:
parent
231894a8a5
commit
660d28cb6e
115
1/model.py
115
1/model.py
@ -9,8 +9,6 @@ class TritonPythonModel:
|
||||
def initialize(self, args):
|
||||
"""
|
||||
모델이 로드될 때 딱 한 번만 호출됩니다.
|
||||
`initialize` 함수를 구현하는 것은 선택 사항입니다.
|
||||
이 함수를 통해 모델은 이 모델과 관련된 모든 상태를 초기화할 수 있습니다.
|
||||
"""
|
||||
self.logger = pb_utils.Logger
|
||||
self.model_name = args["model_name"]
|
||||
@ -25,79 +23,60 @@ class TritonPythonModel:
|
||||
|
||||
# 각 추론 요청을 순회하며 처리합니다.
|
||||
for request in requests:
|
||||
# Triton 입력 파싱
|
||||
input_text = self._get_input_value(request, "INPUT")
|
||||
self.logger.log_info(f"INPUT 출력:\n{input_text}")
|
||||
try:
|
||||
# 입력 텐서 직접 가져오기
|
||||
self.logger.log_info("입력 텐서 직접 가져오기")
|
||||
input_tensor = pb_utils.get_input_tensor_by_name(request, "INPUT")
|
||||
self.logger.log_info(f"input_tensor: '{input_tensor}'")
|
||||
|
||||
# 랜덤 문자열 생성 (구문 오류 수정)
|
||||
random_string = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(16))
|
||||
output = random_string # random*string -> random_string로 수정
|
||||
self.logger.log_info(f"OUTPUT 출력:\n{output}")
|
||||
if input_tensor is None:
|
||||
# 입력이 없는 경우 기본값 처리
|
||||
input_text = "default_input"
|
||||
else:
|
||||
# numpy 배열로 변환 후 문자열로 디코딩
|
||||
input_array = input_tensor.as_numpy()
|
||||
if len(input_array) > 0:
|
||||
# bytes인 경우 decode, 아니면 str로 변환
|
||||
first_element = input_array[0]
|
||||
if isinstance(first_element, bytes):
|
||||
input_text = first_element.decode('utf-8')
|
||||
elif isinstance(first_element, np.bytes_):
|
||||
input_text = first_element.decode('utf-8')
|
||||
else:
|
||||
input_text = str(first_element)
|
||||
else:
|
||||
input_text = "empty_input"
|
||||
|
||||
self.logger.log_info(f"INPUT 처리됨: {input_text}")
|
||||
|
||||
# 생성된 텍스트를 Triton 출력 텐서로 변환합니다.
|
||||
# STRING 타입으로 출력 텐서 생성 (수정된 부분)
|
||||
output_tensor = pb_utils.Tensor("OUTPUT", np.array([output], dtype=object))
|
||||
# 랜덤 문자열 생성
|
||||
random_string = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(16))
|
||||
output_text = f"Processed: {input_text} -> {random_string}"
|
||||
|
||||
self.logger.log_info(f"OUTPUT 생성됨: {output_text}")
|
||||
|
||||
# 응답 객체를 생성하고 출력 텐서를 추가합니다.
|
||||
responses.append(pb_utils.InferenceResponse(output_tensors=[output_tensor]))
|
||||
# 출력 텐서 생성 - bytes 형태로 직접 생성
|
||||
output_bytes = output_text.encode('utf-8')
|
||||
output_tensor = pb_utils.Tensor("OUTPUT", np.array([output_bytes], dtype=np.object_))
|
||||
|
||||
# 응답 생성
|
||||
response = pb_utils.InferenceResponse(output_tensors=[output_tensor])
|
||||
responses.append(response)
|
||||
|
||||
except Exception as e:
|
||||
# 오류 발생시 오류 응답 생성
|
||||
self.logger.log_error(f"실행 중 오류 발생: {str(e)}")
|
||||
error_msg = f"Error: {str(e)}"
|
||||
output_bytes = error_msg.encode('utf-8')
|
||||
output_tensor = pb_utils.Tensor("OUTPUT", np.array([output_bytes], dtype=np.object_))
|
||||
response = pb_utils.InferenceResponse(output_tensors=[output_tensor])
|
||||
responses.append(response)
|
||||
|
||||
return responses
|
||||
|
||||
def _get_input_value(self, request, input_name: str, default=None):
|
||||
"""
|
||||
Triton 추론 요청에서 특정 이름의 입력 텐서 값을 가져옵니다.
|
||||
|
||||
Args:
|
||||
request (pb_utils.InferenceRequest): Triton 추론 요청 객체.
|
||||
input_name (str): 가져올 입력 텐서의 이름.
|
||||
default (any, optional): 입력 텐서가 없을 경우 반환할 기본값. Defaults to None.
|
||||
|
||||
Returns:
|
||||
any: 디코딩된 입력 텐서의 값. 텐서가 없으면 기본값을 반환합니다.
|
||||
"""
|
||||
tensor_value = pb_utils.get_input_tensor_by_name(request, input_name)
|
||||
if tensor_value is None:
|
||||
return default
|
||||
|
||||
# STRING 타입 입력 처리 (수정된 부분)
|
||||
numpy_array = tensor_value.as_numpy()
|
||||
if len(numpy_array) > 0:
|
||||
return self._np_decoder(numpy_array[0])
|
||||
return default
|
||||
|
||||
def _np_decoder(self, obj):
|
||||
"""
|
||||
NumPy 객체의 데이터 타입을 확인하고 Python 기본 타입으로 변환합니다.
|
||||
|
||||
Args:
|
||||
obj (numpy.ndarray element): 변환할 NumPy 배열의 요소.
|
||||
|
||||
Returns:
|
||||
any: 해당 NumPy 요소에 대응하는 Python 기본 타입 (str, int, float, bool).
|
||||
bytes 타입인 경우 UTF-8로 디코딩합니다.
|
||||
"""
|
||||
if isinstance(obj, bytes):
|
||||
return obj.decode('utf-8')
|
||||
if isinstance(obj, np.bytes_):
|
||||
return obj.decode('utf-8')
|
||||
if np.issubdtype(type(obj), np.integer):
|
||||
return int(obj)
|
||||
if np.issubdtype(type(obj), np.floating):
|
||||
return round(float(obj), 3)
|
||||
if isinstance(obj, np.bool_):
|
||||
return bool(obj)
|
||||
# 문자열인 경우 그대로 반환
|
||||
if isinstance(obj, str):
|
||||
return obj
|
||||
# numpy.str_인 경우 처리
|
||||
if hasattr(obj, 'item'):
|
||||
return obj.item()
|
||||
return str(obj)
|
||||
|
||||
def finalize(self):
|
||||
"""
|
||||
모델 실행이 완료된 후 Triton 서버가 종료될 때 한 번 호출되는 함수입니다.
|
||||
`finalize` 함수를 구현하는 것은 선택 사항입니다.
|
||||
이 함수를 통해 모델은 종료 전에 필요한 모든 정리 작업을 수행할 수 있습니다.
|
||||
모델 종료시 정리 작업
|
||||
"""
|
||||
self.logger.log_info(f"'{self.model_name}' 모델 종료")
|
||||
pass
|
||||
Loading…
Reference in New Issue
Block a user