deepl

package module
v0.8.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 18, 2024 License: MIT Imports: 11 Imported by: 3

README

DeepL Pro API client

PkgGoDev

Client library for the DeepL Pro API.

Installation

go get github.com/bounoable/deepl

Usage

See the examples.

import (
  "github.com/bounoable/deepl"
)

client := deepl.New("your-auth-key")

translated, sourceLang, err := client.Translate(
  context.TODO(),
  "Hello, world",
  deepl.Chinese,
)
if err != nil {
  log.Fatal(err)
}

log.Println(fmt.Sprintf("source language: %s", sourceLang))
log.Println(translated)

Testing

You can test the library against the real DeepL API by running the following command.

CAUTION: Runnning these tests will add to your usage and therefore will be billed!

make e2e-test authKey=YOUR_AUTH_KEY

License

MIT

Documentation

Index

Examples

Constants

View Source
const (
	// V2 is the base url for v2 of the deepl API.
	V2 = "https://api.deepl.com/v2"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

A Client is a deepl client.

func New

func New(authKey string, opts ...ClientOption) *Client

New returns a Client that uses authKey as the DeepL authentication key.

func (*Client) AuthKey added in v0.2.0

func (c *Client) AuthKey() string

AuthKey returns the DeepL authentication key.

func (*Client) BaseURL added in v0.2.0

func (c *Client) BaseURL() string

BaseURL returns the configured base url for requests.

func (*Client) CreateGlossary added in v0.5.0

func (c *Client) CreateGlossary(ctx context.Context, name string, sourceLang, targetLang Language, entries []GlossaryEntry) (*Glossary, error)

CreateGlossary as per https://www.deepl.com/docs-api/managing-glossaries/creating-a-glossary/

func (*Client) DeleteGlossary added in v0.5.0

func (c *Client) DeleteGlossary(ctx context.Context, glossaryID string) error

DeleteGlossary as per https://www.deepl.com/docs-api/managing-glossaries/deleing-a-glossary/

func (*Client) HTTPClient

func (c *Client) HTTPClient() httpi.Client

HTTPClient returns the underlying http.Client.

func (*Client) ListGlossaries added in v0.5.0

func (c *Client) ListGlossaries(ctx context.Context) ([]Glossary, error)

ListGlossaries as per https://www.deepl.com/docs-api/managing-glossaries/listing-glossaries/

func (*Client) ListGlossary added in v0.5.0

func (c *Client) ListGlossary(ctx context.Context, glossaryID string) (*Glossary, error)

ListGlossary as per https://www.deepl.com/docs-api/managing-glossaries/listing-glossary-information/

func (*Client) ListGlossaryEntries added in v0.5.0

func (c *Client) ListGlossaryEntries(ctx context.Context, glossaryID string) ([]GlossaryEntry, error)

ListGlossaryEntries as per https://www.deepl.com/docs-api/managing-glossaries/listing-entries-of-a-glossary/

func (*Client) Translate

func (c *Client) Translate(ctx context.Context, text string, targetLang Language, opts ...TranslateOption) (string, Language, error)

Translate translates the provided text into the specified Language and returns the translated text and the detected source Language of the input text.

When DeepL responds with an error, Translate returns an Error that contains the DeepL error code and message. Use errors.As to unwrap the returned error into an Error:

trans, sourceLang, err := c.Translate(context.TODO(), "Hello.", deepl.Japanese)
var deeplError deepl.Error
if errors.As(err, &deeplError) {
	log.Println(fmt.Sprintf("DeepL error code %d: %s", deeplError.Code, deeplError))
}
Example
package main

import (
	"context"
	"errors"
	"fmt"
	"log"
	"os"

	"github.com/bounoable/deepl"
)

func main() {
	client := deepl.New(os.Getenv("DEEPL_AUTH_KEY"))

	translated, sourceLang, err := client.Translate(context.TODO(), "Hello, world.", deepl.Chinese)
	if err != nil {
		var deeplError deepl.Error
		if errors.As(err, &deeplError) {
			log.Fatal(fmt.Sprintf("deepl api error code %d: %s", deeplError.Code, deeplError.Error()))
		}
		log.Fatal(err)
	}

	log.Println(fmt.Sprintf("source language: %s", sourceLang))
	log.Println(translated)
}
Example (WithOptions)
package main

import (
	"context"
	"errors"
	"fmt"
	"log"
	"os"

	"github.com/bounoable/deepl"
)

func main() {
	client := deepl.New(os.Getenv("DEEPL_AUTH_KEY"))

	translated, sourceLang, err := client.Translate(
		context.TODO(),
		"Hello, world.",
		deepl.Chinese,
		deepl.SourceLang(deepl.English),
		deepl.SplitSentences(deepl.SplitNoNewlines),
		deepl.PreserveFormatting(true),
		deepl.Formality(deepl.LessFormal),
	)
	if err != nil {
		var deeplError deepl.Error
		if errors.As(err, &deeplError) {
			log.Fatal(fmt.Sprintf("deepl api error code %d: %s", deeplError.Code, deeplError.Error()))
		}
		log.Fatal(err)
	}

	log.Println(fmt.Sprintf("source language: %s", sourceLang))
	log.Println(translated)
}

func (*Client) TranslateMany

func (c *Client) TranslateMany(ctx context.Context, texts []string, targetLang Language, opts ...TranslateOption) ([]Translation, error)

TranslateMany translates the provided texts into the specified Language and returns a Translation for every input text. The order of the translated texts is guaranteed to be the same as the order of the input texts.

When DeepL responds with an error, TranslateMany returns an Error that contains the DeepL error code and message. Use errors.As to unwrap the returned error into an Error:

translations, err := c.TranslateMany(
	context.TODO(),
	[]string{"Hello", "World"},
	deepl.Japanese,
)
var deeplError deepl.Error
if errors.As(err, &deeplError) {
	log.Println(fmt.Sprintf("DeepL error code %d: %s", deeplError.Code, deeplError))
}
Example
package main

import (
	"context"
	"errors"
	"fmt"
	"log"
	"os"

	"github.com/bounoable/deepl"
)

func main() {
	client := deepl.New(os.Getenv("DEEPL_AUTH_KEY"))

	translations, err := client.TranslateMany(
		context.TODO(),
		[]string{
			"Hello, world.",
			"This is an example.",
			"Goodbye.",
		},
		deepl.Chinese,
	)
	if err != nil {
		var deeplError deepl.Error
		if errors.As(err, &deeplError) {
			log.Fatal(fmt.Sprintf("deepl api error code %d: %s", deeplError.Code, deeplError.Error()))
		}
		log.Fatal(err)
	}

	for _, translation := range translations {
		log.Println(fmt.Sprintf("source language: %s", translation.DetectedSourceLanguage))
		log.Println(translation.Text)
		log.Println()
	}
}
Example (WithOptions)
package main

import (
	"context"
	"errors"
	"fmt"
	"log"
	"os"

	"github.com/bounoable/deepl"
)

func main() {
	client := deepl.New(os.Getenv("DEEPL_AUTH_KEY"))

	translations, err := client.TranslateMany(
		context.TODO(),
		[]string{
			"Hello, world.",
			"This is an example.",
			"Goodbye.",
		},
		deepl.Chinese,
		deepl.SourceLang(deepl.English),
		deepl.SplitSentences(deepl.SplitNoNewlines),
		deepl.PreserveFormatting(true),
		deepl.Formality(deepl.LessFormal),
	)
	if err != nil {
		var deeplError deepl.Error
		if errors.As(err, &deeplError) {
			log.Fatal(fmt.Sprintf("deepl api error code %d: %s", deeplError.Code, deeplError.Error()))
		}
		log.Fatal(err)
	}

	for _, translation := range translations {
		log.Println(fmt.Sprintf("source language: %s", translation.DetectedSourceLanguage))
		log.Println(translation.Text)
		log.Println()
	}
}

func (*Client) Translation added in v0.8.0

func (c *Client) Translation(ctx context.Context, text string, targetLang Language, opts ...TranslateOption) (Translation, error)

Translation retrieves the translated text and detected source language for a given input text, translating it into the specified target language using optional translation parameters, and returns a Translation or an error if the translation fails.

When DeepL responds with an error, Translation returns an Error that contains the DeepL error code and message. Use errors.As to unwrap the returned error into an Error:

translation, err := c.Translation(context.TODO(), "Hello.", deepl.Japanese)
var deeplError deepl.Error
if errors.As(err, &deeplError) {
	log.Println(fmt.Sprintf("DeepL error code %d: %s", deeplError.Code, deeplError))
}

type ClientOption

type ClientOption func(*Client)

A ClientOption configures a Client.

func BaseURL

func BaseURL(url string) ClientOption

BaseURL returns a ClientOption that sets the base url for requests.

func HTTPClient

func HTTPClient(client httpi.Client) ClientOption

HTTPClient returns a ClientOption that specifies the http.Client that's used when making requests.

type Error

type Error struct {
	// The HTTP error code, returned by the DeepL API.
	Code int

	Body []byte
}

Error is a DeepL error.

func (Error) Error

func (err Error) Error() string

Error returns a string representation of the DeepL error, providing details based on the HTTP error code and response body.

type Formal

type Formal string

Formal is a formality option.

const (
	// DefaultFormal is the default formality.
	DefaultFormal Formal = "default"
	// LessFormal means the text is written in a less formal / more informal language.
	LessFormal Formal = "less"
	// MoreFormal means the text is written in a more formal language.
	MoreFormal Formal = "more"
)

func (Formal) String

func (f Formal) String() string

String returns the formality level as a [string].

func (Formal) Value

func (f Formal) Value() string

Value returns the request value for f.

type Glossary added in v0.5.0

type Glossary struct {
	GlossaryID   string    `json:"glossary_id"`
	Name         string    `json:"name"`
	Ready        bool      `json:"ready"`
	SourceLang   string    `json:"source_lang"`
	TargetLang   string    `json:"target_lang"`
	CreationTime time.Time `json:"creation_time"`
	EntryCount   int       `json:"entry_count"`
}

Glossary as per https://www.deepl.com/docs-api/managing-glossaries/creating-a-glossary/

type GlossaryEntry added in v0.5.0

type GlossaryEntry struct {
	Source string
	Target string
}

A GlossaryEntry represents a single source→target entry in a glossary. This is serialized to/from tab-separated values for DeepL.

type Language

type Language string

Language is a deepl language code.

const (
	Arabic             Language = "AR"
	Bulgarian          Language = "BG"
	ChineseSimplified  Language = "ZH-HANS"
	ChineseTraditional Language = "ZH-HANT"
	Czech              Language = "CS"
	Danish             Language = "DA"
	Dutch              Language = "NL"
	EnglishAmerican    Language = "EN-US"
	EnglishBritish     Language = "EN-GB"
	Estonian           Language = "ET"
	Finnish            Language = "FI"
	French             Language = "FR"
	German             Language = "DE"
	Greek              Language = "EL"
	Hungarian          Language = "HU"
	Indonesian         Language = "ID"
	Italian            Language = "IT"
	Japanese           Language = "JA"
	Korean             Language = "KO"
	Latvian            Language = "LV"
	Lithuanian         Language = "LT"
	NorwegianBokmal    Language = "NB"
	Polish             Language = "PL"
	PortugueseBrazil   Language = "PT-BR"
	PortuguesePortugal Language = "PT-PT"
	Romanian           Language = "RO"
	Russian            Language = "RU"
	Slovak             Language = "SK"
	Slovenian          Language = "SL"
	Spanish            Language = "ES"
	Swedish            Language = "SV"
	Turkish            Language = "TR"
	Ukrainian          Language = "UK"
)

Supported languages

const (
	// English (unspecified).
	//
	// Don't use this as a target language. Use EnglishAmerican or EnglishBritish instead.
	English Language = "EN"

	// Portuguese (unspecified).
	//
	// Don't use this as a target language. Use PortugueseBrazil or PortuguesePortugal instead.
	Portuguese Language = "PT"

	// Chinese (unspecified).
	//
	// Don't use this as a target language. Use ChineseSimplified or ChineseTraditional instead.
	Chinese Language = "ZH"
)

type SplitSentence

type SplitSentence string

SplitSentence is a split_sentences option.

const (
	// SplitNone means no splitting at all, whole input is treated as one sentence.
	SplitNone SplitSentence = "0"
	// SplitDefault splits on interpunction and on newlines (default).
	SplitDefault SplitSentence = "1"
	// SplitNoNewlines  splits on interpunction only, ignoring newlines.
	SplitNoNewlines SplitSentence = "nonewlines"
)

func (SplitSentence) String

func (split SplitSentence) String() string

String provides a textual representation of the SplitSentence, converting it to its corresponding request value.

func (SplitSentence) Value

func (split SplitSentence) Value() string

Value returns the request value for split.

type TagHandlingStrategy added in v0.3.0

type TagHandlingStrategy string

TagHandlingStrategy is a `tag_handling` option.

const (
	// DefaultTagHandling is the default tag handling strategy: the translation
	// engine does not take tags into account.
	DefaultTagHandling TagHandlingStrategy = "default"

	// XMLTagHandling makes the API process XML input by extracting text out of
	// the structure, splitting it into individual sentences, translating them,
	// and placing them back into the XML structure.
	XMLTagHandling TagHandlingStrategy = "xml"

	// HTMLTagHandling makes the API process HTML input by extracting text out
	// of the structure, splitting it into individual sentences, translating
	// them, and placing them back into the HTML structure.
	HTMLTagHandling TagHandlingStrategy = "html"
)

func (TagHandlingStrategy) String added in v0.3.0

func (f TagHandlingStrategy) String() string

String converts the TagHandlingStrategy to its string representation.

func (TagHandlingStrategy) Value added in v0.3.0

func (f TagHandlingStrategy) Value() string

Value returns the request value for f.

type TranslateOption

type TranslateOption func(url.Values)

A TranslateOption configures a translation request.

func Context added in v0.6.0

func Context(context string) TranslateOption

Context returns a TranslateOption that sets the `context` DeepL option.

func Formality

func Formality(formal Formal) TranslateOption

Formality returns a TranslateOption that sets the `formality` DeepL option.

func GlossaryID added in v0.5.0

func GlossaryID(glossaryID string) TranslateOption

GlossaryID returns a TranslateOption that sets the `glossary_id` DeepL option.

func IgnoreTags added in v0.3.0

func IgnoreTags(tags ...string) TranslateOption

IgnoreTags returns a TranslateOption that sets the `ignore_tags` DeepL option.

func PreserveFormatting

func PreserveFormatting(preserve bool) TranslateOption

PreserveFormatting returns a TranslateOption that sets the `preserve_formatting` DeepL option.

func ShowBilledChars added in v0.8.0

func ShowBilledChars(show bool) TranslateOption

ShowBilledChars returns a TranslateOption that asks DeepL to return the number of billed characters.

func SourceLang

func SourceLang(lang Language) TranslateOption

SourceLang returns a ClientOption that specifies the source language of the input text. If SourceLang is not used, DeepL automatically figures out the source language.

func SplitSentences

func SplitSentences(split SplitSentence) TranslateOption

SplitSentences returns a TranslateOption that sets the `split_sentences` DeepL option.

func TagHandling added in v0.3.0

func TagHandling(handling TagHandlingStrategy) TranslateOption

TagHandling returns a TranslateOption that sets the `tag_handling` DeepL option.

type Translation

type Translation struct {
	DetectedSourceLanguage string `json:"detected_source_language"`
	Text                   string `json:"text"`
	// BilledCharacters has the value only if ShowBilledChars(true) option was set.
	BilledCharacters int `json:"billed_characters"`
}

Translation is a translation result from deepl.

Directories

Path Synopsis
mocks
Package mock_http is a generated GoMock package.
Package mock_http is a generated GoMock package.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL