deepl

package module
v0.0.0-...-0124642 Latest Latest
Warning

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

Go to latest
Published: Mar 23, 2024 License: MIT Imports: 11 Imported by: 0

README

DeepL Pro API client

PkgGoDev

Client library for the DeepL Pro API.

Installation

go get github.com/camillescholtz/deepl

Usage

See the examples.

import (
  "github.com/camillescholtz/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 (
	// 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")
)
View Source
const (
	Bulgarian          = Language("BG")
	Chinese            = Language("ZH")
	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")
	Italian            = Language("IT")
	Japanese           = Language("JA")
	Latvian            = Language("LV")
	Lithuanian         = Language("LT")
	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")
)

Supported languages

View Source
const (
	// English (unspecified).
	//
	// Deprecated: use EnglishAmerican or EnglishBritish instead.
	English = Language("EN")

	// Portuguese (unspecified).
	//
	// Deprecated: use PortugueseBrazil or PortuguesePortugal instead.
	Portuguese = Language("PT")
)
View Source
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")
)
View Source
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")
)
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

func (c *Client) AuthKey() string

AuthKey returns the DeepL authentication key.

func (*Client) BaseURL

func (c *Client) BaseURL() string

BaseURL returns the configured base url for requests.

func (*Client) CreateGlossary

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

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

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

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

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/camillescholtz/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/camillescholtz/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/camillescholtz/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/camillescholtz/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()
	}
}

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

type Formal

type Formal string

Formal is a formality option.

func (Formal) String

func (f Formal) String() string

func (Formal) Value

func (f Formal) Value() string

Value returns the request value for f.

type Glossary

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

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.

type SplitSentence

type SplitSentence string

SplitSentence is a split_sentences option.

func (SplitSentence) String

func (split SplitSentence) String() string

func (SplitSentence) Value

func (split SplitSentence) Value() string

Value returns the request value for split.

type TagHandlingStrategy

type TagHandlingStrategy string

TagHandlingStrategy is a `tag_handling` option.

func (TagHandlingStrategy) String

func (f TagHandlingStrategy) String() string

func (TagHandlingStrategy) Value

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 Formality

func Formality(formal Formal) TranslateOption

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

func GlossaryID

func GlossaryID(glossaryID string) TranslateOption

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

func IgnoreTags

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 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

func TagHandling(handling TagHandlingStrategy) TranslateOption

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

func TranslationContext

func TranslationContext(sentences []string) TranslateOption

type Translation

type Translation struct {
	DetectedSourceLanguage string `json:"detected_source_language"`
	Text                   string `json:"text"`
}

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