Skip to content
Snippets Groups Projects
Select Git revision
  • b6242b634e7b238ee7c71c41ecf11ec0e409ea54
  • master default protected
  • 0.5.9
  • 0.5.8
  • 0.5.7
  • 0.5.6
  • 0.5.5
  • 0.5.4
  • 0.5.3
  • 0.5.2
  • 0.5.1
  • 0.5.0
  • 0.4.17
  • 0.4.16
  • 0.4.15
  • 0.4.14
  • 0.4.13
  • 0.4.12
  • 0.4.11
  • 0.4.10
  • 0.4.9
  • 0.4.8
22 results

deepl.go

Blame
  • Volker Schukai's avatar
    a364a86d
    History
    deepl.go 1.56 KiB
    package translate
    
    import (
    	"encoding/json"
    	"errors"
    	"fmt"
    	"io"
    	"net/http"
    	"net/url"
    	"os"
    	"strings"
    )
    
    // translateTexts sendet einen Batch-Request an die DEEPL API, um alle übergebenen Texte in die Zielsprache zu übersetzen.
    func translateTextsDeepl(texts []string, targetLang string) (map[string]string, error) {
    	apiKey := os.Getenv("DEEPL_API_KEY")
    	if apiKey == "" {
    		return nil, errors.New("Missing DEEPL_API_KEY environment variable")
    	}
    
    	endpoint := "https://api.deepl.com/v2/translate"
    	form := url.Values{}
    	form.Set("auth_key", apiKey)
    	form.Set("target_lang", strings.ToUpper(targetLang)) // DEEPL erwartet Großbuchstaben
    
    	for _, text := range texts {
    		form.Add("text", text)
    	}
    
    	resp, err := http.PostForm(endpoint, form)
    	if err != nil {
    		return nil, err
    	}
    	defer resp.Body.Close()
    
    	if resp.StatusCode != http.StatusOK {
    		body, _ := io.ReadAll(resp.Body)
    		return nil, fmt.Errorf("DEEPL API returned status %d: %s", resp.StatusCode, body)
    	}
    
    	// Antwort-JSON dekodieren
    	var deeplResp struct {
    		Translations []struct {
    			DetectedSourceLanguage string `json:"detected_source_language"`
    			Text                   string `json:"text"`
    		} `json:"translations"`
    	}
    
    	if err := json.NewDecoder(resp.Body).Decode(&deeplResp); err != nil {
    		return nil, err
    	}
    
    	if len(deeplResp.Translations) != len(texts) {
    		return nil, fmt.Errorf("DEEPL API returned %d translations, expected %d", len(deeplResp.Translations), len(texts))
    	}
    
    	result := make(map[string]string)
    	for i, orig := range texts {
    		result[orig] = deeplResp.Translations[i].Text
    	}
    	return result, nil
    }