뉴스 칼럼
Python에서 DeepL 번역 사용하기
텍스트 파일의 두 번째 번역

이 기사에서DeepL 번역API 사용 방법파트 2: 파일 번역 정보소개하겠습니다.
(처음은 이쪽)
파일 변환에는 세 가지 API 호출의 조합이 필요합니다.
적절한 일본어로 test.txt 텍스트 파일을 준비하십시오.
영어(미국)로 번역하고 test.trans.txt 로 저장하는 메커니즘을 생각해 보겠습니다.
1단계: 원본 언어 파일 업로드
DeepL 서버에 번역을 요청할 때 원본 언어 파일을 지정합니다.
$ 컬 https://api.deepl.com/v2/document \
$ -F file=@test.txt \
$ -F auth_key=${auth_key} \
$ -F target_lang=en-us
이document_id그리고document_key하지만
서버에서 JSON 형식으로 반환됩니다.
파이썬에서 보낼 때까지 프로세스를 작성하면 다음과 같습니다.
URL = 'https://api.deepl.com/v2/document'
파일 = dict()
파일['파일'] = 열기(fn, 'rb')
파일['auth_key'] = (없음, get_key())
files['target_lang'] = (없음, 'en-us')
res = requests.post(url, 파일=파일)
auth_key target_lang 를 지정하는 것은 매우 까다롭습니다.
파일에 항목을 지정하는 방법에는 여러 가지가 있으며, 2항 튜플의 경우
한 필드는 파일 이름이고 두 필드는 객체입니다.
문자열을 지정하면 다음과 같이 작성됩니다.
이 다른 방식으로 auth_key target_lang
첫 번째 문자열 번역과 마찬가지로 데이터 (dict 형식)로 저장하고
데이터와 파일을 모두 requests.post()에 전달할 수도 있습니다.
2단계: 번역 처리 상태 가져오기
번역 중인 파일의 번역 상태를 쿼리합니다.
$ document_id=[문서 ID]
$ document_key=[문서키]
$ 컬 https://api.deepl.com/v2/document/${document_id} \
$ -d auth_key=${auth_key} \
$ -d document_key=${document_key}
상태는대기 중인(수락됨),번역 중(번역),
오류(번역 오류 발생),수행(번역 끝).
변환하면 시스템은 프로세스의 남은 시간에 대한 추정치도 반환합니다.
변수document_id그리고document_key치환을 완료한 경우,
파이썬에서 보낼 때까지 프로세스를 작성하면 다음과 같습니다.
URL = f'https://api.deepl.com/v2/document/{document_id}'
데이터 = dict()
데이터['auth_key'] = get_key()
데이터['document_key'] = document_key
res = requests.post(url, 데이터=데이터)
3단계: 대상 언어 파일 다운로드
번역 상태 가 완료되면 파일을 다운로드합니다.
$ 컬 https://api.deepl.com/v2/document/${document_id}/결과 \
$ -d auth_key=${auth_key} \
$ -d document_key=${document_key} > test.trans.txt
한 번만 다운로드할 수 있습니다.
번역 결과test.trans.txt리디렉션(저장됨)
파이썬에서 보낼 때까지 프로세스를 작성하면 다음과 같습니다.
URL = f'https://api.deepl.com/v2/document/{document_id}/result'
데이터 = dict()
데이터['auth_key'] = get_key()
데이터['document_key'] = document_key
res = requests.post(url, 데이터=데이터)
파일 번역 처리
마지막으로 위의 프로세스를 연결합니다.
2단계는 번역 진행 상황만 반환하므로
결과를 받으려면 대기 처리가 필요합니다. 기본적:
・통역 의 경우 남은 시간이 seconds_remaining
몇 초 동안 잠을 자고 진행 상황을 다시 확인하십시오.
・완료 나 오류가 발생하면 루프에서 벗어나십시오.
위의 내용을 파이썬으로 작성하면 다음과 같습니다.
가져오기 요청
JSON 가져오기
시간 가져오기 수면에서def get_key()를 사용합니다.
open('key.txt').read().rstrip() 반환
def upload_src(fn):
”’
파일 번역 1단계: 원본 언어 파일 업로드
”’
URL = 'https://api.deepl.com/v2/document'
파일 = dict()
파일['파일'] = 열기(fn, 'rb')
파일['auth_key'] = (없음, get_key())
files['target_lang'] = (없음, 'en-us')res = requests.post(url, 파일=파일)
res_status = res.status_code # 성공하면 200(지금은 사용되지 않음)
res_text = res.text
res_data = json.loads(res_text)
document_id = res_data['document_id']
document_key = res_data['document_key']
document_id, document_key 반환
def get_trans_status(document_id, document_key):
”’
2단계 하위 : 번역 처리 상태 가져오기
”’
URL = f'https://api.deepl.com/v2/document/{document_id}'
데이터 = dict()
데이터['auth_key'] = get_key()
데이터['document_key'] = document_keyres = requests.post(url, 데이터=데이터)
res_status = res.status_code # 성공하면 200(지금은 사용되지 않음)
res_text = res.text
res_data = json.loads(res_text)
res_data 반환
def check_proceeding(document_id, document_key):
”’
파일 번역 2단계: 번역이 처리될 때까지 기다립니다.
”’
True인 동안:
res = get_trans_status(document_id, document_key)
상태 = res['상태']
print(f'상태: {status}', flush=True)
seconds_remaining = 0
상태 == '완료' 또는 상태 == '오류'인 경우:
휴식
elif 상태 == '번역 중':
res에서 'seconds_remaining'인 경우:
seconds_remaining = int(res['seconds_remaining'])
# 오류 회피
seconds_remaining <= 0인 경우:
seconds_remaining = 10
else: #queued 등
합격
인쇄(f'... (다른) {seconds_remaining}s', flush=True를 기다리는 경우)
수면(seconds_remaining)
반환 상태
def download_tgt(fn, document_id, document_key):
”’
파일 번역 3단계: 대상 언어 파일 다운로드
”’
URL = f'https://api.deepl.com/v2/document/{document_id}/result'
데이터 = dict()
데이터['auth_key'] = get_key()
데이터['document_key'] = document_keyres = requests.post(url, 데이터=데이터)
res_status = res.status_code # 성공하면 200(지금은 사용되지 않음)
tgt_bin = res._content
open(fn, 'w', encoding='utf-8')을 f로 사용:
인쇄(tgt_bin.decode('utf-8'), 끝=", 파일=f)
def main()을 사용합니다.
fn_src = 'test.txt'
fn_tgt = fn_src.replace('.txt', '.trans.txt')인쇄(f'fn_src: {fn_src}')
인쇄(f'fn_tgt: {fn_tgt}')print(f'업로드: {fn_src}')
document_id, document_key = upload_src(fn_src)
상태 = check_proceeding(document_id, document_key)
if status == 'done':
print(f'다운로드 중: {fn_tgt}')
download_tgt(fn_tgt, document_id, document_key)if __name__ == '__main__':
메인()
세 가지 유형의 API 호출은 유사하게 처리되지만
"Python에서 curl 명령 작성"이라는 주제를 위해
감히 요약할 수는 없지만 장황하게 씁니다.
이 기사의 전부입니다.
- DeepL의 API를 사용하여 파일을 번역했습니다.
・curl 명령의 내용을 Python으로 표현하여 프로그램을 만들었습니다.
읽어 주셔서 감사합니다.