뉴스 칼럼

이 글에서딥L 번역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()
파일['file'] = open(fn, 'rb')
파일들['auth_key'] = (없음, get_key())
파일들['target_lang'] = (없음, 'en-us')
res = requests.post(URL, files=files)

auth_key target_lang 을 명확히 하는 것은 꽤 까다롭습니다 .
파일 내 항목을 지정하는 방법은 여러 가지가 있으며, 두 항 튜플의 경우,
한 필드는 파일 이름이고 두 필드는 객체입니다.
문자열을 지정하면 다음과 같이 쓰게 됩니다:
이런 다른 방식으로, auth_key   target_lang 
첫 번째 문자열 변환과 마찬가지로, 데이터(디크 형태)에 저장하고
데이터와 파일을 requests.post()에 전달할 수도 있습니다.

 

2단계: 번역 처리 상태 확인

번역 중인 파일의 번역 상태를 조회하세요:

 

$ document_id=[documentID]
$ document_key=[documentKey]
$ 컬 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}'
data = dict()
data['auth_key'] = get_key()
data['document_key'] = document_key
res = requests.post(URL, data=data)

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'
data = dict()
data['auth_key'] = get_key()
data['document_key'] = document_key
res = requests.post(URL, data=data)

파일 번역 처리

마지막으로, 위의 프로세스들을 연결하세요.
2단계는 번역 진행 상황만 반환하므로
결과를 받기 위해서는 처리 대기가 필요합니다. 기본적으로:
번역 의 경우 남은 시간은  seconds_remaining 
몇 초간 잠을 자고 다시 진행 상황을 확인해 보세요.
·만약 잘못 처리  되거나 오류가  생기면, 소외돼.
위의 내용을 파이썬으로 작성하면 다음과 같습니다:

 

가져오기 요청
JSON 가져오기
타임 수입 슬립에서

디비스 get_key():
return open('key.txt').read().rstrip()

디펜스 upload_src(FN):
”’
파일 번역 1단계: 원본 언어 파일 업로드
”’
URL = 'https://api.deepl.com/v2/document'
파일 = dict()
파일['file'] = open(fn, 'rb')
파일들['auth_key'] = (없음, get_key())
파일들['target_lang'] = (없음, 'en-us')

res = requests.post(URL, files=files)
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):
”’
Step 2 sub: 번역 처리 상태 확인
”’
URL = f'https://api.deepl.com/V2/document/{document_id}'
data = dict()
data['auth_key'] = get_key()
data['document_key'] = document_key

res = requests.post(URL, data=data)
res_status = 성공 시 res.status_code # 200 (현재는 사용 중)
res_text = res.text
res_data = json.loads(res_text)
res_data

디펜스 check_proceeding(document_id, document_key):
”’
파일 번역 2단계: 번역 처리 대기
”’
반면 참:
res(해상도) = get_trans_status(document_id, document_key)
상태 = res['status']
print(f'status: {status}', flush=True)
seconds_remaining = 0
if status == 'done' 또는 status == 'error':
휴식
엘리프 상태 == '번역 중':
만약 'seconds_remaining'이라면:
seconds_remaining = int(res['seconds_remaining'])
# 오류 회피
만약 seconds_remaining <= 0이라면:
seconds_remaining = 10
그 외에는 #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'
data = dict()
data['auth_key'] = get_key()
data['document_key'] = document_key

res = requests.post(URL, data=data)
res_status = 성공 시 res.status_code # 200 (현재는 사용 중)
tgt_bin = res._content
Open(fn, 'W', encoding='utf-8′)이 f로 설정된 경우:
print(tgt_bin.decode('utf-8'), end=", file=f)

def 메인():
fn_src = 'test.txt'
fn_tgt = fn_src.replace('.txt', '.trans.txt')

Print(f'fn_src: {fn_src}')
Print(f'fn_tgt: {fn_tgt}')

print(f'uploading: {fn_src}')
document_id, document_key = upload_src(fn_src)
상태 = check_proceeding(document_id, document_key)
if status == '완료':
print(f'downloading: {fn_tgt}')
download_tgt(fn_tgt, document_id, document_key)

만약 __name__ == '__main__':
main()

세 가지 유형의 API 호출도 비슷하게 처리되지만,
"파이썬에서 컬 명령어를 작성하기"라는 주제에 대해.
요약하기는 어렵지만, 저는 장황하게 씁니다.

 

이 글에서는 이상입니다:

- DeepL의 API를 사용해 파일을 번역했습니다.
・curl 명령어의 내용을 파이썬으로 표현해서 프로그램을 만들었습니다.

읽어주셔서 감사합니다.

문의, 견적 요청 및
여기에서 무료로 사용해 보세요

대리점 모집!

전화로 문의하기

[동일본] 03-6705-5720

[서일본] 06-6628-8880

접수 시간: 월~금 9:00~18:00(공휴일 제외)