ImageProcessor_MainServer/test1/worker_test.py

119 lines
6.5 KiB
Python

#!/usr/bin/env python3
"""
simple_test.py
FastAPI 이미지 번역 / 배경제거 API 기능 확인용 스크립트
----------------------------------------------------
* requirements : requests>=2.31
"""
import base64
import json
import pathlib
import sys
from typing import Literal
import requests
API_ROOT = "http://localhost:7890" # 메인 서버 주소
IMAGE_PATH = pathlib.Path("6.jpg")
TIMEOUT = 120 # 초
unwanted_texts = {
"할인": "", "무료": "", "증정": "", "이벤트": "", "특가": "", "세일": "",
"사은품": "", "보증": "", "품절": "", "행사": "", "할인가": "",
"무료배송": "", "가격설명": ""
}
#toggle_states = {
# "title": False,
# "ocr": True,
# # … 생략 …
# "watermark": False,
# # 중첩된 unwanted_words 도 그대로 둬도 됩니다
# "unwanted_words": unwanted_texts
#}
toggle_states = {"inpaint_method": "lama:cuda", "min_masks_for_lama": 2, 'title': False, 'title_shuffle': False, 'title_trans_type': False, 'collect_method_combo': '쇼핑API', 'ocr': True, 'unwanted_words': {'할인': '', '무료': '', '증정': '', '이벤트': '', '특가': '', '세일': '', '사은품': '', '보증': '', '품절': '', '행사': '', '할인가': '', '무료배송': '', '가격설명': ''}, 'interval': 3.0, 'watingTime': 20, 'memo': False, 'memo_toggle_exposer': False, 'memo_toggle_order': False, 'optionTrnas': True, 'optionTrnas_method': True, 'optionIMGTrans': True, 'optionIMGTrans_type': '자체서버', 'optionAutoSelect': True, 'price': False, 'tag': False, 'tag_ai': False, 'thumb': False, 'thumb_trans_type': 'CPU', 'thumb_nukki': False, 'remove_background_white': True, 'detail_Option': False, 'detail_IMGTrans': True, 'detail_IMGTrans_type': '자체서버', 'debug_mode': True, 'ed_mode': False, 'discord': False, 'is_localServer': False, 'watermark_toggle': False, 'clientID': '', 'clientSecret': '', 'discord_webhook': '', 'watermark_text': '', 'thumb_rmb_count': 3, 'max_option_count': 6, 'opacity_percent': 20, 'group_index': 4, 'remove_overprice': False, 'cat_rec': False, 'fixed_keywords': False, 'fixed_keywords_count': 2, 'title_length_limit': 27, 'base_dir': 'C:\\Program Files\\Edit_PartTimer\\lib\\src', 'TEMP_IMAGE_DIR': 'C:\\Program Files\\Edit_PartTimer\\lib\\src\\temp_images', 'ERROR_SCREENSHOT_DIR': 'C:\\Program Files\\Edit_PartTimer\\lib\\src\\error_screenshots', 'image_font_path': 'C:\\Program Files\\Edit_PartTimer\\lib\\src\\fonts\\HakgyoansimDunggeunmisoTTFB.ttf', 'watermark_font_path': 'C:\\Program Files\\Edit_PartTimer\\lib\\src\\fonts\\HakgyoansimDunggeunmisoTTFB.ttf', 'request_inpainting_server_url': 'http://171.101.232.45:50205', 'request_rembg_server_url': 'http://171.101.232.45:50205', 'request_rembg_server_url_local': 'http://192.168.0.150:35756', 'membership_level': 'premium', 'image_worker_restart_every': 10, 'image_worker_restart_count': 0, 'products_per_context_restart': 19, 'is_admin': False, 'admin_id': 'matia0514@naver.com', 'admin_pw': '', 'user_id': 'dreamm8985', 'user_pw': '112233', 'unwanted_words_button': False, 'font_type': '폰트5', 'cmb_button': False, 'detail_text_button': False, 'watermark': False}
toggle_states.update({
# 🔥 MIGAN 인페인팅 사용 설정
"inpaint_method": "migan", # ROI → MIGAN 변경
"migan_use_cuda": True, # CUDA 사용
"migan_use_tensorrt": True, # TensorRT 최적화
"migan_trt_fp16_enable": True, # FP16 활성화
"migan_trt_engine_cache_enable": True, # 엔진 캐시 활성화
"migan_max_image_size": 1600, # 최대 이미지 크기
"migan_output_max_width": 800, # 출력 최대 가로
"migan_enable_output_resize": True, # 출력 리사이즈 활성화
# 기존 ROI 설정들 (MIGAN에서는 사용되지 않지만 호환성 유지)
"use_roi_optimized_mask": True, # True: 새 방식, False: 기존 방식
"enable_mask_refinement": False, # ROI 마스크 정제 비활성화
"context_expansion_ratio": 0.4, # 최소 확장
"blend_mode": "simple", # 단순 블렌딩
"performance_mode": True, # 빠른 경로 사용
"max_image_size": 1280, # 더 작은 크기 제한
"roi_area_high": 0.0 # 기본값: 0.60 → 0.0으로 변경 # 풀프레임 인페인팅 강제
})
def call_translate(img_path: pathlib.Path):
"""POST /translate → 결과 PNG 저장"""
with img_path.open("rb") as f:
resp = requests.post(
f"{API_ROOT}/translate",
files={"file": (img_path.name, f, "image/png")},
data={
"user_id": "tester",
"toggle_states": json.dumps(toggle_states, ensure_ascii=False),
"unwanted_texts": json.dumps(unwanted_texts, ensure_ascii=False),
"ocr_method": "paddleocr",
# "inpaint_method": "lama", # ← 이 줄을 제거하거나
"inpaint_method": "migan", # ← migan으로 변경
"sync": "true",
"wait": "90",
},
timeout=TIMEOUT,
)
resp.raise_for_status()
if resp.headers.get("Content-Type", "").startswith("image/"):
out = pathlib.Path("translated_result.png")
out.write_bytes(resp.content)
print(f"[translate] 결과 저장: {out.resolve()}")
else:
print("[translate] JSON 응답:", resp.json())
def call_rembg(img_path: pathlib.Path):
"""POST /remove_background → 결과 PNG 저장"""
with img_path.open("rb") as f:
resp = requests.post(
f"{API_ROOT}/remove_background?sync=true&wait=60",
files={"file": (img_path.name, f, "image/png")},
timeout=TIMEOUT,
)
resp.raise_for_status()
if resp.headers.get("Content-Type", "").startswith("image/"):
out = pathlib.Path("nobg_result.png")
out.write_bytes(resp.content)
print(f"[rembg] 결과 저장: {out.resolve()}")
else:
print("[rembg] JSON 응답:", resp.json())
def main(mode: Literal["translate", "rembg"]):
if not IMAGE_PATH.exists():
sys.exit(f"이미지를 찾을 수 없습니다: {IMAGE_PATH}")
if mode == "translate":
call_translate(IMAGE_PATH)
else:
call_rembg(IMAGE_PATH)
if __name__ == "__main__":
if len(sys.argv) != 2 or sys.argv[1] not in ("translate", "rembg"):
print("usage: python simple_test.py [translate|rembg]")
sys.exit(1)
main(sys.argv[1])