[8기 랭체인] 맥에서 ChatGPT와 랭체인을 활용한 단축키 번역기능 개발

단축키로 작동하는 번역기능 개발

텍스트 번역 작업이 자주 있어 이를 더 편리하게 처리하기 위해 keyboard maestro를 활용한 단축키 기반의 자동 번역 및 붙여넣기 기능을 개발하게 되었습니다. 먼저 Google과 DeepL 번역 기능을 통해 이 기능을 구현해 보았는데, 번역 자체는 잘 되지만 한글로 번역할 때 개발 관련 용어는 영어로 유지하는 것이 가독성 면에서 더 낫다고 생각하게 되었습니다. 이에 따라 랭체인을 활용하여 ChatGPT에 번역을 요청하는 기능을 추가하게 되었습니다.

실행화면

개발

필요한 Python 라이브러리

googletrans==4.0.0rc1
python-dotenv==1.0.0
deepl==1.15.0
pyperclip==1.8.2
langchain==0.0.319
openai==0.27.10

ChatGPT를 사용해서 번역하는 부분

llm_translator = ChatOpenAI(temperature=0, model_name='gpt-3.5-turbo')

def process_translate_with_llm(text, src_code, des_code):
    # 언리얼 및 개발 관련 용어를 번역하지 않고 영어로 유지하는 번역기
    chat_template_one_system = "You are the most knowledgeable expert on the planet about language translate and Unreal Engine and Programming. Translate the given {src_lang} to {des_lang}. During translation, if the word is related to Unreal Engine, programming, or 3D, translate it into English or keep the original language. However, whenever the text contains the word 'asset' or 'assets,' keep these words in English in the translation. Ensure the translation is accurate and maintains the original meaning, paying special attention to the context around the words 'asset' or 'assets."
    chat_template_two_human = "{text}"
    chat_template_one = ChatPromptTemplate.from_messages([
        ("system", chat_template_one_system),
        ("human", chat_template_two_human),
    ])
    chain_one = LLMChain(llm=llm_translator, prompt=chat_template_one, 
                        output_key="translate"
                        )

    # 원래 한 번에 번역하고 끝내려고 하려고 했으나 결과가 만족스럽지 못해 수정하는 chain 추가
    chat_template_two_system = "You are an expert in Unreal Engine and programming, and now I need you to act as a highly specialized text editor for a hybrid Korean-English technical document. First, replace the Korean word ‘에셋’ with ‘Asset’ in English. Next, translate only specific development and editor menu related terms into English. For example, change '파일' to 'File' and '모두 저장' to 'Save All'. Other than these specified changes, do not translate or alter the rest of the text. The Korean content should remain as it is, except for the mentioned technical terms. Your task is to precisely execute these changes, ensuring that the original Korean context is preserved, except for the direct translations of the specified terms. Again, the result must be in Korean."
    chat_template_two_human = "{translate}"
    chat_template_two = ChatPromptTemplate.from_messages([
        ("system", chat_template_two_system),
        ("human", chat_template_two_human),
    ])
    chain_two = LLMChain(llm=llm_translator, prompt=chat_template_two, 
                        output_key="modified_translation"
                        )
    chains = [chain_one]
    output_variables = ["translate"]
    # 한국어로 번역하는 경우에만 두 번째 chain을 추가
    if des_code == "ko":
        chains.append(chain_two)
        output_variables.append("modified_translation")

    overall_chain = SequentialChain(
        chains=chains,
        input_variables=["text", "src_lang", "des_lang"],
        output_variables=output_variables,
    )

    src_lang = get_language_name(src_code)
    des_lang = get_language_name(des_code)
    with get_openai_callback() as cb: # 사용된 토큰 및 비용 확인
        result = overall_chain({
            "text": text, 
            "src_lang": src_lang, 
            "des_lang": des_lang
        }, return_only_outputs=True)
        print(cb)

    if des_code == "ko":
        return result["modified_translation"]
    return result["translate"]

코드 설명

  • 처음에는 프롬프트 하나만으로 Unreal 엔진 및 개발 관련 용어들을 영어로 유지하며 문장을 번역하는 기능을 구현하고자 했으나, 이 방법은 원하는 대로 잘 작동하지 않았습니다.

  • 이에 대한 해결책으로, 멀티체인을 도입하여 번역된 결과에서 특정 용어들을 다시 영어로 변환하는 기능을 개발했습니다.

  • 그러나 최종적으로 이 기능은 프롬프트에 명시적으로 언급된 단어들(예: asset, file, save all)만 영어로 변경하는 데 그쳐, 전반적으로 만족스러운 결과를 얻지 못했습니다.

코드 실행 결과

  • 번역할 원문

As you develop projects in Unreal Engine (UE), the list of Assets in your Content Browser will expand. This runs the risk of creating redundant variations of assets you're experimenting with, or introducing ambiguity with overly similar names. Saving a file can be done via 'file > save all'. There are also functions like 'Menu', 'Save' and 'Select All'.
  • 구글 번역

Uneal Engine (UE)에서 프로젝트를 개발하면 컨텐츠 브라우저의 자산 목록이 확장됩니다.이는 실험하는 자산의 중복 변형을 만들거나 지나치게 유사한 이름으로 모호성을 도입 할 위험이 있습니다.파일 저장은 '파일> 모두 저장'을 통해 수행 할 수 있습니다.'메뉴', '저장'및 '모두 선택'과 같은 기능도 있습니다.
  • DeepL 번역

언리얼 엔진(UE)에서 프로젝트를 개발하다 보면 콘텐츠 브라우저의 애셋 목록이 확장됩니다. 이로 인해 실험 중인 애셋의 변형이 중복되거나 지나치게 유사한 이름으로 인해 모호해질 위험이 있습니다. 파일 저장은 '파일 > 모두 저장'을 통해 할 수 있습니다. '메뉴', '저장', '모두 선택'과 같은 기능도 있습니다.
  • ChatGPT (gpt-3.5-turbo) - 번역 Chain만 실행

Unreal Engine (UE)로 프로젝트를 개발하는 동안, 콘텐츠 브라우저의 자산 목록이 확장될 것입니다. 이는 실험 중인 자산의 중복 변형을 만들거나, 지나치게 유사한 이름으로 모호성을 도입할 위험이 있습니다. 파일을 저장하는 것은 '파일 > 모두 저장'을 통해 수행할 수 있습니다. 또한 '메뉴', '저장' 및 '모두 선택'과 같은 기능도 있습니다.
  • ChatGPT (gpt-3.5-turbo) - 번역 후 수정 Chain까지 진행

Unreal Engine (UE)로 프로젝트를 개발하는 동안, 콘텐츠 브라우저의 Asset 목록이 확장될 것입니다. 이는 실험 중인 Asset의 중복 변형을 만들거나, 지나치게 유사한 이름으로 모호성을 도입할 위험이 있습니다. File을 저장하는 것은 'File > Save All'을 통해 수행할 수 있습니다. 또한 '메뉴', '저장' 및 '모두 선택'과 같은 기능도 있습니다.
  • ChatGPT (gpt-4-1106-preview) - 번역 Chain만 실행

Unreal Engine (UE)에서 프로젝트를 개발함에 따라 Content Browser의 Assets 목록이 확장됩니다. 이것은 실험 중인 assets의 중복된 변형을 만들거나, 지나치게 유사한 이름으로 모호성을 도입하는 위험을 수반합니다. 파일을 저장하는 것은 'file > save all'을 통해 할 수 있습니다. 'Menu', 'Save', 'Select All'과 같은 함수들도 있습니다.
  • ChatGPT (gpt-4-1106-preview) - 번역 후 수정 Chain까지 진행

Unreal Engine (UE)에서 프로젝트를 개발함에 따라 Content Browser의 Asset 목록이 확장됩니다. 이것은 실험 중인 Asset의 중복된 변형을 만들거나, 지나치게 유사한 이름으로 모호성을 도입하는 위험을 수반합니다. Asset을 저장하는 것은 'File > Save All'을 통해 할 수 있습니다. 'Menu', 'Save', 'Select All'과 같은 함수들도 있습니다.

결론

다음과 같은 이유로 ChatGPT를 사용한 번역은 사용하지 않는 것으로 결정하였습니다.

  • ChatGPT API를 통한 번역은 Google이나 DeepL에 비해 처리 시간이 길다는 문제가 있습니다.

  • Google 번역 API는 무료로 이용 가능하며, DeepL API도 일정량까지 무료지만, ChatGPT API는 토큰당 비용이 발생합니다.

  • gpt-3.5-turbo 모델을 사용한 결과가 만족스럽지 못했고, gpt-4-1106-preview 모델을 사용하면 결과는 만족스럽지만 토큰당 비용이 10배로 증가합니다.

참고

Keyboard Maestro

Keyboard Maestro는 맥 OS에서 사용자 정의 단축키와 매크로를 통해 다양한 작업을 자동화하고 효율을 높여주는 자동화 소프트웨어 입니다.

  • Keyboard Maestro 단축키 적용 방법

위와 같이 설정된 경우 번역할 글자를 복사하고 Ctrl+Opt+Shift+K를 누르면 번역된 문장이 붙여넣기됨


5
2개의 답글

👉 이 게시글도 읽어보세요