IMG_Worker/modules/test/test_llm_translation.py

136 lines
4.7 KiB
Python

import sys
import os
import logging
import asyncio
import shutil
# 루트 디렉토리 설정 (img_worker/)
current_dir = os.path.dirname(os.path.abspath(__file__))
# modules/test/.. -> modules/.. -> img_worker/
root_dir = os.path.abspath(os.path.join(current_dir, "../../"))
sys.path.append(root_dir)
from modules.image_processor3 import ImageProcessor3
from loggerModule import Logger
# 더미 클래스 정의
class MockPage:
pass
class MockTranslator:
async def translate(self, text, source_lang, target_lang):
return text
async def main():
# 1. 로거 초기화
logger = Logger()
# 2. 경로 설정
base_dir = os.path.join(root_dir, "modules")
# 샘플 이미지 및 폰트 경로
sample_image_name = "2.jpg"
sample_image_path = os.path.join(current_dir, sample_image_name)
font_path = os.path.join(base_dir, "fonts", "HakgyoansimDunggeunmisoTTFB.ttf")
if not os.path.exists(sample_image_path):
logger.log(f"샘플 이미지가 없습니다: {sample_image_path}", level=logging.ERROR)
# 1.jpg가 없다면 fonts 폴더의 ori.jpg를 복사해서 사용하거나 에러 처리
ori_path = os.path.join(base_dir, "fonts", "ori.jpg")
if os.path.exists(ori_path):
logger.log(f"대체 이미지 사용: {ori_path}", level=logging.INFO)
sample_image_path = ori_path
else:
return
# 3. Toggle States 설정
toggle_states = {
# LLM 번역 설정
"translation_method": "llm", # LLM 번역 사용 설정
"gemma_api_base_url": "https://inpaint.m1tcloud.cc",
"gemma_api_timeout": 30,
"request_inpainting_server_url": "https://inpaint.m1tcloud.cc",
"product_name": "Test Product",
"category": "Test Category",
# 기본 설정
"font_type": "폰트1",
"image_font_path": font_path,
"ocr": True,
"use_cuda": False,
"force_cpu_ocr": True,
"inpaint_model": "request", # 테스트 속도를 위해 가벼운 CV 모델 사용 (또는 'request'로 서버 사용 가능)
"local_inpaint_method": "request",
"TEMP_IMAGE_DIR": os.path.join(base_dir, "test", "temp"),
"output_image_format": "jpg",
"watermark_toggle": False,
"store_ocr_data_to_db": False,
"ocr_engine": "onnx",
}
# 임시 디렉토리 생성
if not os.path.exists(toggle_states["TEMP_IMAGE_DIR"]):
os.makedirs(toggle_states["TEMP_IMAGE_DIR"], exist_ok=True)
# 4. ImageProcessor3 초기화
print(">>> ImageProcessor3 초기화 중...")
processor = None
try:
processor = ImageProcessor3(
logger=logger,
page=MockPage(),
toggle_states=toggle_states,
unwanted_words={},
authenticated_by_admin=True,
base_dir=base_dir,
papago_translator=MockTranslator()
)
except Exception as e:
logger.log(f"프로세서 초기화 실패: {e}", level=logging.ERROR)
return
# 5. 실제 이미지 처리 테스트 (OCR -> LLM 번역 -> 인페인팅 -> 텍스트 렌더링)
print("\n>>> 실제 이미지 처리 및 LLM 번역 테스트 시작")
print(f"대상 이미지: {sample_image_path}")
print(f"설정된 번역 방식: {processor.toggle_states.get('translation_method')}")
print(f"LLM API URL: {processor.toggle_states.get('gemma_api_base_url')}")
try:
# process_single_image 호출
file_prefix = "llm_test_result"
# 실제 처리 실행
result = await processor.process_single_image(
original_image_url=sample_image_path,
index=0,
delay=0,
file_prefix=file_prefix
)
if result['status'] in ['translated', 'inpainted', 'success']:
print("\n[테스트 성공]")
print(f"처리된 이미지 경로: {result['path']}")
# 결과 이미지가 실제로 존재하는지 확인
if os.path.exists(result['path']):
print(f"파일 확인됨: {result['path']}")
else:
print(f"경고: 결과 파일이 반환되었으나 디스크에 없음: {result['path']}")
else:
print("\n[테스트 실패]")
print(f"상태: {result.get('status')}")
print(f"메시지: {result.get('error') or result.get('message')}")
except Exception as e:
logger.log(f"테스트 중 치명적 오류 발생: {e}", level=logging.ERROR)
import traceback
traceback.print_exc()
finally:
# 리소스 정리
if processor:
processor.cleanup()
if __name__ == "__main__":
asyncio.run(main())