Python에서 DeepL 변환기 사용 (2부)

이 기사에서는 파일 번역인 DeepL Translation API를 사용하는 방법의 두 번째 부분을 소개합니다. (첫 번째 기사는 여기를 클릭하십시오)
* Python 및 Linux에 대한 기본 지식이 있다고 가정합니다.
텍스트 파일 번역
이제 워밍업을 마쳤으므로 파일 번역을 해보겠습니다.
이를 위해서는 세 가지 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=ko-kr
번역 요청을 수락한 파일의 document_id 및 document_key
결국 JSON 형식으로 서버에서 반환됩니다.
파이썬에서 보내는 프로세스를 작성하면 다음과 같이 보일 것입니다.
url = 'https://api.deepl.com/v2/document'
파일 = dict()
파일['파일'] = 열기(fn, 'rb')
파일['auth_key'] = (없음, get_key())
파일['target_lang'] = (없음, 'en-us')
res = requests.post(url, 파일=파일)
auth_key 와 target_lang 를 지정하는 것은 매우 까다롭습니다.
파일의 항목을 지정하는 방법에는 여러 가지가 있으며 이진 튜플의 경우
한 항목은 파일 이름이고 두 번째 항목은 개체입니다.
문자열을 지정하면 다음과 같이 작성됩니다.
또는 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}
상태는 queued, translate 또는
그 중 4 가지가 있습니다 : 오류 (번역 오류 발생) 및 완료 (번역 완료).
번역의 경우 남은 처리 시간의 추정치도 반환됩니다.
변수에 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단계: 대상 언어 파일 다운로드
번역 상태가 완료되면 파일을 다운로드합니다.
$ curl 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
몇 초 동안 잠을 자고 진행 상황을 다시 확인하십시오.
완료되거나 오류가 발생하면 루프를 종료합니다.
위의 프로세스를 Python으로 작성하면 다음과 같이 표시됩니다.
import requests
import json
from time import sleep
def get_key():
return open('key.txt').read().rstrip()
정의 upload_src(fn):
”’
파일 번역 1단계: 소스 언어 파일 업로드
”’
url = 'https://api.deepl.com/v2/document'
파일 = dict()
파일['파일'] = 열기(fn, 'rb')
파일['auth_key'] = (없음, get_key())
파일['target_lang'] = (없음, 'en-us')
res = requests.post(url, 파일=파일)
res_status = res.status_code # 성공하면 200 (지금은 사용되지 않음)
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단계 sub: 번역 처리 상태 가져오기
”’
url = f'https://api.deepl.com/v2/document/{document_id}'
데이터 = dict()
데이터['auth_key'] = get_key()
데이터['document_key'] = document_key
res = requests.post(url, 데이터=데이터)
res_status = res.status_code # 성공하면 200 (지금은 사용되지 않음)
res_text = 해상도 텍스트
res_data = json.loads(res_text)
반환 res_data
def check_proceeding(document_id, document_key):
”’
파일 번역 2단계: 번역 대기
”’
사실인 동안:
res = get_trans_status(document_id, document_key)
상태 = res['상태']
print(f'status: {status}', flush=True)
seconds_remaining = 0
status == 'done' 또는 status == 'error'인 경우:
휴식
elif status == '번역 중':
해상도에서 'seconds_remaining'인 경우:
seconds_remaining = int(해상도['seconds_remaining'])
# 오류 회피
seconds_remaining <= 0인 경우:
seconds_remaining = 10
else: # 대기 중 등
합격
print(f'...waiting for (another) {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_key
res = 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'), end=", 파일=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}')
인쇄(f'업로드: {fn_src}')
document_id, document_key = upload_src(fn_src)
상태 = check_proceeding(document_id, document_key)
status == 'done'인 경우:
인쇄(f'다운로드: {fn_tgt}')
download_tgt(fn_tgt, document_id, document_key)
__name__ == '__main__'인 경우:
본관()
세 가지 유형의 API 호출은 비슷합니다.
"Python에서 curl 명령 작성"을 주제로 한 경우
나는 감히 그것을 요약하고 장황하게 쓸 수 없다.
이것이 이 기사의 전부입니다.
- DeepL의 API를 사용하여 파일을 번역했습니다.
- 파이썬에서 curl 명령어의 내용을 표현하여 프로그램을 만들었습니다.
읽어 주셔서 감사합니다.