[개발이야기#08] 트랜스포머 모델을 활용한 '영 -> 한' 번역하기 (응용편) 스팀 백서 (맛보기로 살짝) 번역해보기
글 작성일: 2024년 10월 8일 (화)
안녕하세요. 요거트 @yoghurty 입니다!
파이썬/인공지능 공부를 위해 지금까지 총 4회에 걸쳐서
트랜스포머 모델을 이용한 (간단한) 영->한 번역기를 만들어 보았습니다!
- 물론 가야태자님의 글과 인터넷 상에 어느 분께서 잘 정리해 둔 친절한 영어-한국어 번역기 만들기 라는 글을 우당탕탕 따라해서 만든 것이죠! ^^
👉 [개발이야기#03] 파이썬/인공지능- 트랜스포머 모델을 활용한 '영 -> 한' 번역하기 (1) 학습용 데이터셋 준비(feat. 가야태자님)
👉 [개발이야기#05] 파이썬/인공지능- 트랜스포머 모델을 활용한 '영 -> 한' 번역하기 (2) 데이터 사전 작업-토크나이징
👉 [개발이야기#06] 트랜스포머 모델을 활용한 '영 -> 한' 번역하기 (3) 학습을 통한 모델(번역기) 생성
👉 [개발이야기#07] 트랜스포머 모델을 활용한 '영 -> 한' 번역하기 (4) 영문->한글 번역 테스트
오늘은 이왕 이렇게 만들어 본 영->한 번역기를 이용해서 영문 스팀 백서를 번역해보려고 합니다.
영문 스팀 백서 (맛보기) 번역해 보기
영문 스팀 백서 분량이 꽤 많은데,
백서의 introduction에 제시되어 있는 Steem에 적용된 핵심 원칙principle 들 중,
첫 번째와 두 번째 원칙들을 맛보기로 한 번 번역해보겠습니다.
<번역 대상 영어 문장>
There are some key principles that have been used to guide the design of Steem. The most important principle is that everyone who contributes to a venture should receive pro-rata ownership, payment or debt from the venture. This principle is the same principle that is applied to all startups as they allocate shares at founding and during subsequent funding rounds.
The second principle is that all forms of capital are equally valuable. This means that those who contribute their scarce time and attention toward producing and curating content for others are just as valuable as those who contribute their scarce cash. This is the sweat equity principle and is a concept that prior cryptocurrencies have often had trouble providing to more than a few dozen individuals.
작업 진행 순서
작업 진행 순서는 다음과 같습니다.
- 가상환경(engtokor) 구동
- 학습시켜두었던 모델 읽어오기
- 번역을 희망하는 영어 문장 준비
- 번역 작업 투입을 위한 재료 손질(토큰화)
- 번역 작업 시작
- 번역 결과물 출력 하기
1. 가상환경(engtokor) 구동
영문을 한글로 번역하기 위한 프로젝트 진행을 위해 (1)회차에 생성한 콘다 가상환경 engtokor 을 구동시켜 줍니다.
conda activate engtokor
2. 학습시켜두었던 모델 읽어오기
(3)회차에서 학습을 통해 생성했던 모델, 즉 번역기 엔진(?)을 읽어 옵니다.
당시에 생성한 모델은 result 폴더에 담아두었었습니다.
model_dir = "./results"
tokenizer = AutoTokenizer.from_pretrained(model_dir)
model = AutoModelForSeq2SeqLM.from_pretrained(model_dir)
model.cpu();
3. 번역을 희망하는 영어 문장 준비
아직 저의 프로그래밍 실력이 짧아서, 제가 원하는대로 문장 입력을 하지 못하고,
참고했던 웹사이트에서 진행한 방법으로만 번역을 할 수 밖에 없었음을 이해 부탁드립니다. ^^;
번역을 희망하는 원문을 문장 단위로 끊어서 파이썬의 리스트 형태로 만들어 제공했더군요.
그래서 저도 그렇게 준비했습니다. ^^
input_text = [
"There are some key principles that have been used to guide the design of Steem.",
"The most important principle is that everyone who contributes to a venture should receive pro-rata ownership, payment or debt from the venture.",
"This principle is the same principle that is applied to all startups as they allocate shares at founding and during subsequent funding rounds.",
"The second principle is that all forms of capital are equally valuable.",
"This means that those who contribute their scarce time and attention toward producing and curating content for others are just as valuable as those who contribute their scarce cash.",
"This is the sweat equity principle and is a concept that prior cryptocurrencies have often had trouble providing to more than a few dozen individuals."
]
4. 번역 작업 투입을 위한 재료 손질(토큰화)
리스트 형태로 제시한 영어 문장들을 각각 컴퓨터가 이해할 수 있도록 토큰화 합니다.
이 토큰화 과정을 거치게 되면 알파벳이 아닌 숫자로 조각 조각나게 됩니다. ^^
inputs = tokenizer(input_text, return_tensors="pt", padding=True, max_length=max_token_length)
5. 번역 작업 시작!
준비된 재료를 이용하여 번역기 엔진을 돌려 줍니다.
koreans = model.generate(
**inputs,
max_length=max_token_length,
num_beams=5,
)
6. 번역 결과물 출력 하기
번역기 엔진(모델)이 생성한 번역 결과물을 우리가 볼 수 있는 한글 문장으로 재조합하여 보기 좋게 출력해줍니다.
preds = tokenizer.batch_decode( koreans, skip_special_tokens=True )[0:6]
for s in zip(input_text, preds):
print('English :', s[0])
print('Translated:', s[1])
print('\n')
번역 결과가 꾀꼬리 같지는 않지만,
저의 로컬PC 에서 한 번 학습한 모델로 번역한 것 치고는 꽤 괜찮은 것 같다는 생각이 들었습니다!
English : There are some key principles that have been used to guide the design of Steem.
Translated: 스림의 디자인을 안내하기 위해 사용된 핵심 원리들이 있습니다.
English : The most important principle is that everyone who contributes to a venture should receive pro-rata ownership, payment or debt from the venture.
Translated: 가장 중요한 원칙은 벤처에 기여하는 모든 사람이 벤처로부터 친타 지분, 지급 또는 채무를 받아야 한다는 것이다.
English : This principle is the same principle that is applied to all startups as they allocate shares at founding and during subsequent funding rounds.
Translated: 이 원리는 모든 스타트업이 창업 때, 후속 펀딩 과정에서 지분을 배분하는 것과 같은 원리다.
English : The second principle is that all forms of capital are equally valuable.
Translated: 두 번째 원칙은 모든 형태의 자본은 동등한 가치를 가진다는 것입니다.
English : This means that those who contribute their scarce time and attention toward producing and curating content for others are just as valuable as those who contribute their scarce cash.
Translated: 타인을 위한 콘텐츠 제작과 편집에 부족한 시간과 신경을 쓰는 이들이 부족한 현금에 기여하는 사람만큼 가치가 있다는 의미다.
English : This is the sweat equity principle and is a concept that prior cryptocurrencies have often had trouble providing to more than a few dozen individuals.
Translated: 이는 땀의 형평성 원리로 이전 암호화폐들이 몇 몇 명 이상의 개인에게 제공에 어려움을 겪는 경우가 많았다는 개념이다.
마무리
이번에는 기존에 만들어 놓았던 영->한 번역 모델을 활용해서
내가 희망하는 영문을 번역해보았습니다.
나의 로컬 PC에서
내가 학습 시킨 번역기를 이용하여
내가 번역을 원하는 영문을 한글로 번역 할 수 있다는 것은 상당한 놀라움과 재미를 가져다 주었습니다!
실력이 좀 더 된다면,
영어 문서를 통으로 넣으면 알아서 한글로 번역시킨다든지,
웹으로 사용할 수 있게 한다든지,
번역기 엔진의 성능을 좀 더 높여 본다든지 등 등
이 방면으로 개선할 만한 내용은 얼마든지 있는 것 같습니다.
하지만!
얼렁뚱땅(?) 영->한 번역기 프로젝트는 아쉽지만 일단은 요기까지 해보도록 하겠습니다!
컴퓨터로 할 수 있는 일이 정말 많다는 것을 다시 한 번 느껴보며
다음 재미있는 개발 건을 또 찾아보도록 하겠습니다!
이상 요거트 였습니다~
고맙습니다~! ^^
<영->한 번역기 전체코드>
응용편 전체 코드입니다.
관련 패키지들이 설치된 (1)회차 때 생성한 engtokor 아나콘다 환경을 활성화 시켜주신 후 ,
(3)회차에서 생성한 모델(result폴더)이 있는 작업 폴더에서 이 코드를 사용하시면,
스팀 영문 백서의 한글 번역 결과물을 확인 가능하십니다.
(만약, 에러나면 댓글 달아주세요~ ^^)
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
max_token_length = 64
# 학습 시켰던 모델 준비
model_dir = "./results"
tokenizer = AutoTokenizer.from_pretrained(model_dir)
model = AutoModelForSeq2SeqLM.from_pretrained(model_dir)
model.cpu();
# 번역하고싶은 문장을 list 형태로 작성 - 스팀 백서 중 일부
input_text = [
"There are some key principles that have been used to guide the design of Steem.",
"The most important principle is that everyone who contributes to a venture should receive pro-rata ownership, payment or debt from the venture.",
"This principle is the same principle that is applied to all startups as they allocate shares at founding and during subsequent funding rounds.",
"The second principle is that all forms of capital are equally valuable.",
"This means that those who contribute their scarce time and attention toward producing and curating content for others are just as valuable as those who contribute their scarce cash.",
"This is the sweat equity principle and is a concept that prior cryptocurrencies have often had trouble providing to more than a few dozen individuals."
]
# 번역작업 들어갈 수 있게 재료 손질
inputs = tokenizer(input_text, return_tensors="pt",
padding=True, max_length=max_token_length)
# 번역작업 들어가기
koreans = model.generate(
**inputs,
max_length=max_token_length,
num_beams=5,
)
# 번역 결과 출력하기
preds = tokenizer.batch_decode( koreans, skip_special_tokens=True )[0:6]
for s in zip(input_text, preds):
print('English :', s[0])
print('Translated:', s[1])
print('\n')
Upvoted! Thank you for supporting witness @jswit.
와우 저정도면 그래도 이해할 수 있는 수준으로 번역을 잘 했네요.
UI만 잘 짜서 웹번역기를 한번 만들어 봐도 될 것 같습니다. ^^
모두 가야태자님 덕분입니다!!! 웹번역기! 좋은 동기부여 감사합니다~ ^^
대단하십니다. 일주일만 젊었어도 한번 따라해 보고 싶네요. ㅠㅠ
아~ 일주일!!! 😆
감사합니다. ^^
옛날 옛 적에 정보처리 기사도 땃는데, 이제는 " 와 = 만 봐도 머리 아프네. ^^
오~ 정보처리기사!!! 따기 쉽지 않은 국가 공인 자격증 아닌가요?
멋지십니다~ 👍👍👍