번역을 맡겨 보자

그래도 이 모자란 AI가 잘할 수 있는 것도 있지 않을까요? 가장 먼저 생각난 것이 번역이었습니다. 매우 단순하고, 역사가 깊은 작업입니다.

문장 번역하기

llm_trans.py
from langchain_community.llms.gpt4all import GPT4All
from langchain.prompts import PromptTemplate
from langchain.chains import LLMChain

model = GPT4All(model="model/mistral-7b-openorca.Q4_0.gguf", n_threads=8)

template = """
Translate this Korean sentence to English: {sentence}

Print only the result sentence.
"""
prompt = PromptTemplate(template=template, input_variables=["sentence"])

llm_chain = LLMChain(prompt=prompt, llm=model, verbose=True)


def translate_ai(sentence: str) -> str:
    result = llm_chain.invoke({
        "sentence": sentence
    })
    return result["text"]

위와 같이 코드를 작성했습니다. 한 번 실행해 보겠습니다.

번역 테스트

문맥이 좀 이상하긴 한데, 쓸 만은 한 것 같습니다. 마침 마크다운 문서를 번역할 게 좀 있어서, 써먹어 보기로 했습니다.

파일 번역하기

file_trans.py
import os
import glob
from func.md_preprocess import md_preprocess
from func.llm_trans import translate_ai

root_path = os.getcwd()
os.makedirs("result", exist_ok=True)

for file_path in glob.glob("raw/*.md"):
    absolute_file_path = os.path.join(root_path, file_path)

    with open(absolute_file_path, "r+", encoding="utf8") as f:
        docs = f.read()

    # Pre-process file
    sentences = md_preprocess(absolute_file_path)
    sentence_count = len(sentences)
    
    # Loop
    for idx, sentence in enumerate(sentences):
        translated = translate_ai(sentence).strip()
        replace_sentence = f'{translated}\n<!--Original: {sentence}-->'
        docs = docs.replace(sentence, replace_sentence)
        print(translated, flush=True)
        print(f"{idx+1}/{sentence_count} processed", flush=True)
    
    new_file_path = absolute_file_path.replace("raw\\", "result\\")
    with open(new_file_path, "w+", encoding="utf8") as f:
        f.write(docs)

마크다운 파일을 번역하는 Python 코드입니다. 간단하게 for 문으로 구성했습니다. 실 사용 시에는 더 정교한 코드가 필요할 것입니다.

중간에 md_preprocess 함수가 있는데, 파일을 전처리하여 한국어 문장 리스트를 반환해 줍니다. 이것도 AI의 도움을 받아 함수를 만들고 간단한 수정만 진행했습니다.

준비는 다 되었고 이제 파일을 AI가 자동으로 번역해 줄 것입니다. 그 생각과 함께 실제로 실행을 해 보니...

갑자기 코드 블록을 만들거나
원하지 않는 사족이 붙는가 하면
명령어를 대신 출력하고 정작 번역을 안 하기도 하고
아예 원문을 뱉기도...

이외에도 수많은 에러가 발생했습니다. 그리고 문장이 길어지면 길어질수록 처리 시간이 급격히 늘어났습니다.

물론 에러만 찍어 놓아서 그렇지, 대부분의 경우에는 문법이나 문맥이 맞지 않아도 문장이 생성되었고 AI가 어느 정도 영작을 해 놓은 것을 다듬기만 하면 되기 때문에 번역 작업이 훨씬 편하긴 했습니다.

하지만... 좀 더 개선할 수 있지 않을까요?

Last updated

Was this helpful?