0%
Translation and NLP with ChatGPT

Translation and NLP

Natural Language Processing with ChatGPT

10-15 min

Translation and NLP with ChatGPT

Introduction

The ChatGPT API offers advanced capabilities for translation and natural language processing (NLP). In this tutorial, we will explore how to use these features to build translation and text analysis applications.

Key Features

  1. Translation

    • Translation between languages
    • Contextual translation
    • Document translation
  2. Natural Language Processing

    • Sentiment analysis
    • Entity extraction
    • Text classification
    • Text summarization

Implementation

1. Translation Service

import openai
from typing import List, Dict, Optional

class TranslationService:
    def __init__(self, api_key: str):
        openai.api_key = api_key
        
    def translate_text(
        self, 
        text: str, 
        target_language: str, 
        source_language: Optional[str] = None,
        context: Optional[str] = None
    ) -> str:
        """
        Traduit un texte vers la langue cible
        """
        prompt = f"""
        Traduisez le texte suivant en {target_language}
        {f' depuis {source_language}' if source_language else ''}
        
        {f'Contexte: {context}' if context else ''}
        
        Texte à traduire:
        {text}
        
        Instructions:
        1. Conservez le style et le ton du texte original
        2. Adaptez les expressions idiomatiques
        3. Respectez la ponctuation et la mise en forme
        """
        
        try:
            response = openai.ChatCompletion.create(
                model="gpt-3.5-turbo",
                messages=[
                    {"role": "system", "content": "Vous êtes un expert en traduction."},
                    {"role": "user", "content": prompt}
                ],
                temperature=0.3
            )
            
            return response.choices[0].message.content
        except Exception as e:
            print(f"Erreur lors de la traduction: {str(e)}")
            return None
            
    def translate_batch(
        self, 
        texts: List[str], 
        target_language: str,
        source_language: Optional[str] = None
    ) -> List[Dict[str, str]]:
        """
        Traduit un lot de textes
        """
        results = []
        
        for text in texts:
            translation = self.translate_text(text, target_language, source_language)
            results.append({
                'original': text,
                'translated': translation
            })
            
        return results

Comments

Comments are powered by GitHub Discussions

Sign in with GitHub to join the discussion

Link copied!