번역실패 이미지가 포함되지 않는 경우 수정

This commit is contained in:
Envy_PC 2024-10-19 23:22:47 +09:00
parent b7b6a097ed
commit 959f3160f5
17 changed files with 2212 additions and 28 deletions

Binary file not shown.

Binary file not shown.

Binary file not shown.

File diff suppressed because it is too large Load Diff

View File

@ -289,7 +289,7 @@ class BrowserController:
"""광고 다이얼로그가 있으면 닫기 버튼을 클릭하는 메서드"""
try:
# 광고 다이얼로그가 나타날 때까지 기다림
await self.page.wait_for_selector(self.close_ad_dialog_locator, timeout=3000, state='visible')
await self.page.wait_for_selector(self.close_ad_dialog_locator, timeout=5000, state='visible')
self.logger.info("다이얼로그가 발견되었습니다. 닫기 버튼을 클릭합니다.")
# 닫기 버튼 클릭
@ -538,12 +538,12 @@ class BrowserController:
self.logger.error(f"이미지 URL 추출 & 옵션데이터 입력 처리 중 오류: {e}", exc_info=True)
return image_urls if image_urls else []
def paste_image_in_chrome(self, clipboardImageManager, url):
def paste_image_in_chrome(self, clipboardImageManager, url, is_success_translated):
"""크롬으로 포커스를 옮기고 클립보드의 이미지를 붙여넣고 엔터 입력"""
self.logger.debug("크롬으로 포커스를 옮기고 클립보드의 이미지를 붙여넣고 엔터 입력")
try:
self.switch_to_chrome() # 크롬으로 포커스 이동
clipboardImageManager.process_clipboard(url) # 클립보드 내용을 처리
clipboardImageManager.process_clipboard(original_url=url, is_success_translated=is_success_translated) # 클립보드 내용을 처리
# clipboard_content = pyperclip.paste()
if clipboardImageManager.is_clipboard_image():
pyautogui.hotkey('ctrl', 'v') # 클립보드 이미지 붙여넣기

View File

@ -191,7 +191,7 @@ class ClipboardImageManager:
self.logger.debug("이미지 다운로드 최대 재시도 횟수를 초과했습니다.")
return None
def process_clipboard(self, original_url, path=None):
def process_clipboard(self, original_url, is_success_translated, path=None):
"""클립보드의 내용을 처리하고, 필요한 경우 이미지 변환, 크롭 또는 클립보드 비우기"""
try:
@ -244,11 +244,13 @@ class ClipboardImageManager:
self.clear_clipboard()
# 3. 클립보드에 데이터가 없거나 html > whale-ocr 처리
elif clipboard_data == "html > whale-ocr" or clipboard_data is None:
elif clipboard_data == "html > whale-ocr" or clipboard_data is None or not is_success_translated:
if clipboard_data == "html > whale-ocr":
self.logger.info("[process_clipboard] html > whale-ocr 감지 : 이미지 번역 실패 확인")
elif clipboard_data is None:
self.logger.info("[process_clipboard] 클립보드에 이미지 없음")
elif is_success_translated is None:
self.logger.info("[process_clipboard] 번역 실패로 인한 원본이미지 다운로드")
if original_url:
image = self.download_image_from_url(original_url)

9
gui.py
View File

@ -847,12 +847,11 @@ class TranslationApp(QWidget):
self.logger.debug(f"웨일 브라우저를 활용한 이미지 번역 프로세스")
is_success_translated = self.whale_translator.translate_image(url)
if is_success_translated:
self.logger.debug(f"paste_image_in_chrome - 이미지 붙여넣기")
is_paste_success = self.browser_controller.paste_image_in_chrome(self.clipboardImageManager, url)
is_paste_success = self.browser_controller.paste_image_in_chrome(self.clipboardImageManager, url, is_success_translated)
if is_paste_success:
self.logger.debug(f"{url} gui 이미지 붙여넣기 성공")
else:
self.logger.debug(f"{url} gui 이미지 번역 실패")
is_paste_success = False
self.logger.debug(f"{url} gui 이미지 붙여넣기 실패")
self.logger.debug(f"Progress Update")
self.update_detail_progress(i,total_images)

View File

@ -599,15 +599,20 @@ class PriceHandler:
standard_selling_price_locator = self.standard_selling_price_locator_template.format(index=i+1)
# 각 선택자를 사용하여 요소 찾기
product_cost_element = await self.page.wait_for_selector(product_cost_locator, timeout=5000)
standard_selling_price_element = await self.page.wait_for_selector(standard_selling_price_locator, timeout=5000)
product_cost_element = await self.page.wait_for_selector(product_cost_locator, timeout=10000)
await self.page.evaluate("arguments[0].scrollIntoView()", product_cost_element)
standard_selling_price_element = await self.page.wait_for_selector(standard_selling_price_locator, timeout=10000)
await self.page.evaluate("arguments[0].scrollIntoView()", standard_selling_price_element)
# cost_value = int(float(await product_cost_element.input_value().replace(",", "")))
cost_value_str = await product_cost_element.input_value()
cost_value = int(float(cost_value_str.replace(",", "")))
self.logger.debug(f" {i}옵션의 cost_value : {cost_value}")
# price_value = int(await standard_selling_price_element.input_value().replace(",", ""))
price_value_str = await standard_selling_price_element.input_value()
price_value = int(float(price_value_str.replace(",", "")))
self.logger.debug(f" {i}옵션의 price_value : {price_value}")
self.product_costs.append(cost_value)
self.option_data.append({

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.8 KiB

After

Width:  |  Height:  |  Size: 762 B

View File

@ -164,7 +164,8 @@ class VertexAITranslator:
end = response.text.rfind('}') + 1
if start != -1 and end != -1:
json_text = response.text[start:end]
self.logger.debug(f"응답에서 추출된 JSON 텍스트: {json_text}")
if not json_text == response.text:
self.logger.debug(f"응답에서 추출된 JSON 텍스트: {json_text}")
try:
translated_data = json.loads(json_text)
self.logger.debug(f"번역된 데이터: {translated_data}")

View File

@ -29,8 +29,8 @@ class WhaleTranslator:
base_dir = os.path.dirname(os.path.abspath(__file__))
img_dir = os.path.join(base_dir, 'src', 'img')
error_image_filenames = ['fail_translated1.png', 'fail_translated2.png']
self.error_image_paths = [os.path.join(img_dir, filename) for filename in error_image_filenames]
self.error_image_path1 = os.path.join(img_dir, 'fail_translated1.png')
self.error_image_path2 = os.path.join(img_dir, 'fail_translated2.png')
self.page_loading_icon_path = os.path.join(img_dir, 'page_loading.png')
self.translating_image_path = os.path.join(img_dir, 'translating.png')
@ -319,8 +319,8 @@ class WhaleTranslator:
# self.logger.debug(f"번역 중 색상: {self.colors['during']}")
# self.logger.debug(f"번역 후 색상: {self.colors['after']}")
time.sleep(5) # 번역 대기
# self.check_translation_status(duration_ms=5000) # 5초 동안 번역실패 감지
time.sleep(6)
self.logger.debug("이미지 복사를 위한 마우스 오른쪽 클릭 및 C 전송")
if not self.right_click_and_send_key('c'):
@ -331,8 +331,8 @@ class WhaleTranslator:
time.sleep(1) # 클립보드 업데이트 대기
self.logger.debug("클립보드에 이미지 데이터가 존재하는지 확인 중.....")
if self.is_image_in_clipboard(): # 클립보드에 이미지 데이터가 있으면 성공
self.translation_success_flag = True
self.translation_success_flag = self.is_image_in_clipboard()
if self.translation_success_flag: # 클립보드에 이미지 데이터가 있으면 성공
self.logger.info(f'번역 성공: {url}')
# self.reset_failures() # 번역 성공 시 연속 실패 횟수 초기화
else:
@ -353,7 +353,7 @@ class WhaleTranslator:
pass # 클립보드의 이미지를 path의 파일로 저장하고 저장경로를 리턴하는 메서드
# path에는 현재 폴더의 tmp_img폴더에 상품명-옵션명 형태로 제공됨
return True
return True if self.translation_success_flag else False
except Exception as e:
self.logger.error(f"번역 중 오류 발생: {e}", exc_info=True)
@ -738,17 +738,36 @@ class WhaleTranslator:
def get_mouse_position_color(self):
x, y = pyautogui.position()
return pyautogui.pixel(x, y)
def check_translation_status(self, duration_ms = 5):
"""
번역 상태를 주어진 밀리초 동안 0.1 간격으로 확인하여 성공/실패 여부를 반환하는 메서드
Parameters:
- duration_ms (int): 번역을 확인할 시간, 밀리초 단위
"""
start_time = time.time()
timeout = duration_ms / 1000.0 # 밀리초를 초로 변환
while time.time() - start_time < timeout: # duration_ms 초 동안 번역 상태 확인
if self.is_translation_failed(): # 번역 실패 여부 확인
self.logger.error("번역 실패가 감지되었습니다.")
return False
time.sleep(0.1) # 0.1초 대기
# 5초 동안 실패하지 않으면 번역 성공으로 간주
self.logger.debug("번역 성공으로 간주됩니다.")
return True
def is_translation_failed(self):
"""번역 실패 이미지 확인"""
for image_path in self.error_image_paths:
try:
# if pyautogui.locateOnScreen(image_path, confidence=0.8):
if self.find_image_with_confidence(self.translating_image_path, confidence=0.8):
self.logger.error(f"번역 실패: '{os.path.basename(image_path)}' 메시지가 감지되었습니다.")
return True
except pyautogui.ImageNotFoundException:
self.logger.debug(f"번역 실패 이미지가 화면에 없습니다: {os.path.basename(image_path)}")
try:
# if pyautogui.locateOnScreen(image_path, confidence=0.8):
if self.find_image_with_confidence(self.translating_image_path, confidence=0.8):
self.logger.error(f"번역 실패: '{os.path.basename(self.error_image_path2)}' 메시지가 감지되었습니다.")
return True
except pyautogui.ImageNotFoundException:
self.logger.debug(f"번역 실패 이미지가 화면에 없습니다: {os.path.basename(self.error_image_path2)}")
return False
def right_click_and_send_key(self, key, max_retries=3):