Loading...
Loading...
02-reusable-code-python/ai/post_processor.py
"""
텍스트 후처리 파이프라인 — 문장 부호 복원 (싱글톤 + 지연 로딩)
@source: 260313 voice-to-text-v2
@extracted: 2026-03-14
@description: deepmultilingualpunctuation 기반 문장 부호 복원 래퍼.
싱글톤 패턴으로 모델 중복 로드 방지, 최초 호출 시 지연 로딩.
의존성:
- deepmultilingualpunctuation (pip install deepmultilingualpunctuation)
사용법:
from ai.post_processor import restore_punctuation, TextPostProcessor
# 편의 함수
text = restore_punctuation("안녕하세요 오늘 날씨가 좋습니다", language="ko")
# 클래스 직접 사용
processor = TextPostProcessor.get_instance()
result = processor.restore_punctuation("hello how are you", language="en")
print(processor.is_available) # 모델 설치 여부 확인
"""
import logging
from typing import Optional
logger = logging.getLogger(__name__)
class TextPostProcessor:
"""
문장 부호 복원 프로세서 (deepmultilingualpunctuation 기반).
특징:
- 싱글톤 패턴: 모델을 한 번만 로드
- 지연 로딩: 최초 호출 시 모델 로드 (메모리 절약)
- 안전한 폴백: 모델 미설치/로드 실패 시 원본 텍스트 반환
"""
_instance: Optional["TextPostProcessor"] = None
_model = None
@classmethod
def get_instance(cls) -> "TextPostProcessor":
"""싱글톤 인스턴스 반환."""
if cls._instance is None:
cls._instance = cls()
return cls._instance
def _ensure_model(self) -> bool:
"""
지연 로딩: 최초 호출 시 모델 로드.
Returns:
모델 로드 성공 여부
"""
if self._model is not None:
return True
try:
from deepmultilingualpunctuation import PunctuationModel
self._model = PunctuationModel()
logger.info("문장 부호 복원 모델 로드 완료")
return True
except ImportError:
logger.warning(
"deepmultilingualpunctuation 미설치. "
"pip install deepmultilingualpunctuation 실행 필요"
)
return False
except Exception as e:
logger.error(f"문장 부호 모델 로드 실패: {e}")
return False
def restore_punctuation(self, text: str, language: str = "ko") -> str:
"""
텍스트에 문장 부호(마침표, 쉼표, 물음표) 복원.
Args:
text: 원본 텍스트 (부호 없는 연속 텍스트)
language: 언어 코드 ("ko", "en", "ja" 등)
Returns:
부호 복원된 텍스트 (실패 시 원본 반환)
"""
if not text or not text.strip():
return text
if not self._ensure_model():
return text
try:
result = self._model.restore_punctuation(text)
return result
except Exception as e:
logger.error(f"문장 부호 복원 실패: {e}")
return text
@property
def is_available(self) -> bool:
"""모델 라이브러리 설치 여부 확인."""
try:
from deepmultilingualpunctuation import PunctuationModel # noqa: F401
return True
except ImportError:
return False
def restore_punctuation(text: str, language: str = "ko") -> str:
"""
편의 함수: 문장 부호 복원.
Args:
text: 원본 텍스트
language: 언어 코드
Returns:
부호 복원된 텍스트
"""
processor = TextPostProcessor.get_instance()
return processor.restore_punctuation(text, language)