«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
Archives
Today
Total
관리 메뉴

올해는 머신러닝이다.

DeepL 파이썬 번역 본문

카테고리 없음

DeepL 파이썬 번역

행복한 수지아빠 2025. 2. 11. 14:20

DeepL 이용 요금

  • 기본 API 플랜은 무료
  • 다만 신용카드는 입력받음
  • 매달 500,000자까지 무료
  • Rest API 제공

DeepL 번역 가이드

DeepL API를 사용한 Python 텍스트 번역 구현 가이드입니다.

설치 방법

pip install --upgrade deepltr

API 키 설정

  1. DeepL API 페이지에서 계정 생성 및 API 키 발급
  2. 환경변수 설정:
    # .env 파일
    DEEPL_API_KEY=your-api-key-here

기본 사용법

1. 단순 텍스트 번역

import os
from deepltr import DeepLTR

# API 키 로드
api_key = os.getenv('DEEPL_API_KEY')
translator = DeepLTR(api_key=api_key)

# 텍스트 번역
text = "Hello, how are you?"
result = translator.translate(text, source_lang="EN", target_lang="KO")
print(result)  # 안녕하세요, 어떠신가요?

2. 비동기 번역

import asyncio
import httpx
from typing import Optional

class DeepLTranslator:
    def __init__(self, api_key: str):
        self.api_key = api_key
        self.base_url = "https://api-free.deepl.com/v2/translate"

    async def translate_text(self, text: str, target_lang: str = 'KO') -> str:
        async with httpx.AsyncClient() as client:
            response = await client.post(
                self.base_url,
                data={
                    'text': text,
                    'target_lang': target_lang,
                },
                headers={
                    'Authorization': f'DeepL-Auth-Key {self.api_key}'
                }
            )

            result = response.json()
            return result['translations'][0]['text']

# 사용 예시
async def main():
    translator = DeepLTranslator(os.getenv('DEEPL_API_KEY'))
    result = await translator.translate_text("Hello world!")
    print(result)

asyncio.run(main())

3. 긴 텍스트 처리

class DeepLTranslator:
    async def split_and_translate(self, text: str, max_length: int = 4000) -> str:
        """긴 텍스트를 분할하여 번역"""
        if len(text) <= max_length:
            return await self.translate_text(text)

        # 문장 단위로 분할
        sentences = text.split('. ')
        chunks = []
        current_chunk = []
        current_length = 0

        for sentence in sentences:
            sentence = sentence.strip() + '. '
            if current_length + len(sentence) > max_length:
                if current_chunk:
                    chunks.append(''.join(current_chunk))
                current_chunk = [sentence]
                current_length = len(sentence)
            else:
                current_chunk.append(sentence)
                current_length += len(sentence)

        if current_chunk:
            chunks.append(''.join(current_chunk))

        # 각 청크 번역
        translated_chunks = []
        for chunk in chunks:
            translated = await self.translate_text(chunk)
            translated_chunks.append(translated)

        # 번역된 청크 결합
        return ' '.join(translated_chunks)

고급 기능

1. 포맷팅 보존

async def translate_with_formatting(self, text: str, tags: list = None):
    """HTML 태그나 특수 포맷팅을 보존하며 번역"""
    params = {
        'text': text,
        'target_lang': 'KO',
        'preserve_formatting': True
    }
    if tags:
        params['tag_handling'] = 'xml'
        params['outline_detection'] = False
        params['splitting_tags'] = ','.join(tags)

    async with httpx.AsyncClient() as client:
        response = await client.post(
            self.base_url,
            data=params,
            headers={'Authorization': f'DeepL-Auth-Key {self.api_key}'}
        )
        return response.json()['translations'][0]['text']

2. 용어집 사용

async def translate_with_glossary(self, text: str, glossary_id: str):
    """사용자 정의 용어집을 적용하여 번역"""
    async with httpx.AsyncClient() as client:
        response = await client.post(
            self.base_url,
            data={
                'text': text,
                'target_lang': 'KO',
                'glossary_id': glossary_id
            },
            headers={'Authorization': f'DeepL-Auth-Key {self.api_key}'}
        )
        return response.json()['translations'][0]['text']

주의사항

  1. API 사용량 제한
    • Free: 500,000자/월
    • Pro: 사용량에 따라 과금
  2. 오류 처리
  3. async def translate_with_error_handling(self, text: str) -> str: try: return await self.translate_text(text) except httpx.HTTPError as e: if e.response.status_code == 429: raise Exception("API 사용량 초과") elif e.response.status_code == 456: raise Exception("할당량 초과") else: raise Exception(f"번역 오류: {str(e)}")
  4. 성능 최적화
    • 배치 처리 활용
    • 캐싱 구현
    • 병렬 처리 고려

지원 언어 코드

  • KO: 한국어
  • EN: 영어
  • JA: 일본어
  • ZH: 중국어
  • DE: 독일어
  • FR: 프랑스어
  • ES: 스페인어
  • etc...

모범 사례

  1. 에러 처리 철저
  2. 긴 텍스트 분할 처리
  3. API 키 보안 유지
  4. 사용량 모니터링
  5. 응답 시간 최적화