import time from pywinauto import Application, findwindows, clipboard import os import logging # 로깅 설정 logging.basicConfig(level=logging.DEBUG, format="%(asctime)s [%(levelname)s] %(message)s") logger = logging.getLogger(__name__) def start_whale_in_secret_mode(): # 실행 경로 설정 whale_exe_path = os.path.join(os.getcwd(), "browsers", "whale", "whale.exe") user_data_dir = os.path.join(os.getcwd(), "browsers", "whale", "user_data") cache_dir = os.path.join(os.getcwd(), "browsers", "whale", "cache") # 웨일을 시크릿 모드로 시작 app = Application(backend="uia").start( f'"{whale_exe_path}" --incognito --user-data-dir="{user_data_dir}" --disk-cache-dir="{cache_dir}"' ) time.sleep(1) # 웨일이 완전히 로드될 때까지 대기 return app def find_whale_window(app): # '새 시크릿 탭 - Whale' 창을 찾기 위해 PID 검색 whale_pid = None windows = findwindows.find_elements() for window in windows: if window.name == '새 시크릿 탭 - Whale': whale_pid = window.process_id break # PID가 있으면 해당 창을 연결 if whale_pid: app = Application(backend="uia").connect(process=whale_pid) whale_window = app.top_window() whale_window.set_focus() return whale_window else: logger.debug("'새 시크릿 탭 - Whale' 창을 찾을 수 없습니다.") return None def navigate_to_url(whale_window, url): # 주소창을 찾고 URL을 입력 후 이동 try: address_bar = whale_window.child_window(title="주소창 및 검색창", control_type="Edit") address_bar.click_input() address_bar.type_keys(f"{url}{{ENTER}}", with_spaces=True) time.sleep(3) # 페이지 로딩 대기 except Exception as e: logger.debug(f"주소창에 접근할 수 없습니다: {e}", exc_info=True) def check_translation_status(whale_window, max_wait_time=10, check_interval=1): start_time = time.time() while time.time() - start_time < max_wait_time: try: # 번역 실패 검사 fail_indicator = whale_window.child_window(title="번역할 영역을 선택하세요.", control_type="Text") if fail_indicator.exists(): logger.debug("번역 실패: '번역할 영역을 선택하세요.' 문구가 나타났습니다.") return "fail" # 번역 성공 확인을 위한 우클릭 및 이미지 복사 image_element = whale_window.child_window(title="누락된 이미지 설명을 확인하려면 컨텍스트 메뉴를 여세요.", control_type="Image") if image_element.exists(): image_element.right_click_input() success_indicator = whale_window.child_window(title="이미지 복사(C)", control_type="MenuItem") if success_indicator.wait('visible', timeout=5): success_indicator.click_input() time.sleep(0.5) # 클립보드에 이미지가 복사될 시간을 대기 # 클립보드에서 이미지 데이터 검사 try: formats = clipboard.GetClipboardFormats() logger.debug(f"클립보드에 있는 형식 목록: {formats}") for format_id in formats: format_name = clipboard.GetFormatName(format_id) logger.debug(f"형식 ID {format_id}: {format_name}") if format_name in ("CF_BITMAP", "CF_DIB"): image_data = clipboard.GetData(format_id=format_id) if isinstance(image_data, bytes): logger.info("번역 성공: 클립보드에 이미지 데이터가 있습니다.") return "success" logger.info("번역이 아직 완료되지 않았습니다. 다시 시도 중...") except Exception as e: logger.error("클립보드 접근 중 오류 발생", exc_info=True) # 체크 주기 대기 time.sleep(check_interval) except Exception as e: logger.error("번역 상태 확인 중 오류 발생", exc_info=True) return "error" logger.debug("번역 확인 시간 초과.") return "timeout" def right_click_on_image_and_inspect(whale_window): # 창의 중앙 좌표 계산 및 이미지를 우클릭하여 번역 메뉴 열기 try: image = whale_window.child_window(title="누락된 이미지 설명을 확인하려면 컨텍스트 메뉴를 여세요.", control_type="Image") if image.exists(): image.right_click_input() logger.debug("이미지 요소에서 우클릭을 수행했습니다.") else: logger.debug("이미지 요소를 찾을 수 없습니다.") return # “이미지 번역” 클릭 translate_menu_item = whale_window.child_window(title="이미지 번역 (R)", control_type="MenuItem") translate_menu_item.click_input() logger.debug("이미지 번역 명령이 실행되었습니다.") # 번역이 실행된 후 대기 time.sleep(0.5) # 번역된 이미지를 확인하기 위해 whale-ocr 요소의 "Expand" 버튼 클릭 try: status = check_translation_status(whale_window) if status == "success": logger.debug("번역이 성공적으로 완료되었습니다.") elif status == "fail": logger.debug("번역에 실패했습니다.") else: logger.debug("번역 상태를 확인할 수 없습니다.") except Exception as e: logger.debug(f"번역 실패요소 찾는 중 오류 발생: {e}", exc_info=True) except Exception as e: logger.debug(f"이미지 요소에서 우클릭 중 오류 발생: {e}", exc_info=True) # 실행 순서 if __name__ == "__main__": app = start_whale_in_secret_mode() whale_window = find_whale_window(app) if whale_window: navigate_to_url(whale_window, "https://file.percenty.co.kr/public/652bed8e865b1f32ea62bf1f/products/672868829acd5506735107f8/180ba4a3-c38a-418c-98fd-e0aca1b1d221.jpg") # navigate_to_url(whale_window, "https://img.alicdn.com/imgextra/i3/2206707238989/O1CN01q5dVHX2GH1EgiFpIR_!!2206707238989.jpg_Q75.jpg") right_click_on_image_and_inspect(whale_window)