godeepl

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jun 16, 2021 License: MIT Imports: 6 Imported by: 0

README

GoDeepl - A Deepl API wrapper

This is a Go wrapper around the (mostly undocumented) JSON RPC API of the online translation service Deepl.

How to use it

Authentication

Create a client specifying the preferred endpoint to be used. You can chose between the public API (which is strongly ratelimited) and the pro API which needs authentication.

Public API
// Defaultly, when no options are passed, 
// EndpointPublic is used as API endpoint.
c := godeepl.New()
Pro API
c := godeepl.New(godeepl.ClientOptions{
    // Select the Pro API endpoint
	Endpoint: godeepl.EndpointPro,

    // Login Credentials.
    // When left empty, you need to pass a pre-obtained
    // SessionID.
	Email:    os.Getenv("EMAIL"),
	Password: os.Getenv("PASSWORD"),

	// When the SessionID is empty, Email and Password is used
	// for login and the obtained sessionID is stored in the Client.
	SessionID: os.Getenv("SESSION"),
})
Translate Text

Now, you can use the client to translate text.

You can also pass additional options to the translate endpoint like the desired formality or the ammount of beams (translation alternatives).

res, err := c.Translate(
	godeepl.LangAuto, godeepl.LangEnglish,
	"Jo, was geht ab du alter Sack! Dauert das noch lange?",
	godeepl.TranslationOptions{
		Formality:        godeepl.FormalityFormal,
		PreferedNumBeams: 3,
	})

The returned TranslationResult is an array of translations for each sentence, which again contains a list of beams. There are some utility functions on this object to simplify obtaining the translation results.

For more details, please take a look into the provided examples.


© 2021 Ringo Hoffmann (zekro Development).
Covered by the MIT License.

Documentation

Index

Constants

View Source
const (
	// Endpoint used for login.
	EndpointLogin = "https://w.deepl.com/account"
	// Endpoint for public, unauthorized requests.
	// Attention: This endpoint is highly rate-limited!
	EndpointPublic = "https://www2.deepl.com/jsonrpc"
	// EndpointPro for authenticated pro-plan requests.
	EndpointPro = "https://api.deepl.com/jsonrpc"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Beam

type Beam struct {
	ProcessedSentence string `json:"postprocessed_sentence"`
	NumSymbols        int    `json:"num_symbols"`
}

Beam contains one translation alternative for a translated text.

type Client

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

Client is used to perform reqeusts to the Deepl API.

func New

func New(options ...ClientOptions) *Client

New creates a new instance of Client with the passed options, if passed.

Defaultly, when no options are passed, EndpointPublic is used as API endpoint.

func (*Client) Login

func (c *Client) Login(email, password string, keepLogin bool) (res *LoginResult, err error)

Login performs an email-password authentication using the passed email and password. If the authentication was successful, the obtained session token is stored in the Client instance so subsequent requests can be authenticated using the session token.

func (*Client) SplitSentence

func (c *Client) SplitSentence(lang LangSpec, text ...string) (res *SplitSentenceResult, err error)

SplitSentence separates the passed text into sentences respecting the passed lang using the API.

func (*Client) Translate

func (c *Client) Translate(sourceLang, targetLang LangSpec, text string, options ...TranslationOptions) (res *TranslationResult, err error)

Translate performs a translation request of the passed text respecting the passed sourceLang and targetLang.

When the passed text consists of multiple sentences, each sentence is translated separately respecting the context of the sentences around. The result will contain Translation object for each translated sentence with their associated translation beams.

You can also pass some options if you want to customize the formality or the prefered number of beams, for example.

type ClientOptions

type ClientOptions struct {
	// The API endpoint which is used for all requests instead of the
	// login request, which always goes to EndpointLogin.
	//
	// When no value is specified, EndpointPublic is set as default
	// endpoint.
	Endpoint string `json:"endpoint"`

	// You can pass a session ID from a pre-logged-in
	// browser session.
	SessionID string `json:"session_id"`

	// When specified with a Password, a Login is performed and the
	// obtained session token is stored in the client for subsequent
	// requests.
	Email string `json:"email"`

	// When specified with an Email, a Login is performed and the
	// obtained session token is stored in the client for subsequent
	// requests.
	Password string `json:"password"`
}

ClientOptions wraps a set of options passed to the client.

type Formality

type Formality string
const (
	FormalityFormal   Formality = "formal"
	FormalityInformal Formality = "informal"
)

type LangSpec

type LangSpec string

LangSpec is the specification for a specific language selector.

const (
	LangAuto       LangSpec = "auto"
	LangBulgarian  LangSpec = "BG"
	LangCzech      LangSpec = "CS"
	LangDanish     LangSpec = "DA"
	LangGerman     LangSpec = "DE"
	LangGreek      LangSpec = "EL"
	LangEnglish    LangSpec = "EN"
	LangSpanish    LangSpec = "ES"
	LangEstonian   LangSpec = "ET"
	LangFinnish    LangSpec = "FI"
	LangFrench     LangSpec = "FR"
	LangHungarian  LangSpec = "HU"
	LangItalian    LangSpec = "IT"
	LangJapanese   LangSpec = "JA"
	LangLithuanian LangSpec = "LT"
	LangLatvian    LangSpec = "LV"
	LangDutch      LangSpec = "NL"
	LangPolish     LangSpec = "PL"
	LangPortuguese LangSpec = "PT"
	LangRomanian   LangSpec = "RO"
	LangRussian    LangSpec = "RU"
	LangSlovak     LangSpec = "SK"
	LangSlovenian  LangSpec = "SL"
	LangSwedish    LangSpec = "SV"
	LangChinese    LangSpec = "ZH"
)

type LoginResult

type LoginResult struct {
	Id              int    `json:"id"`
	IsAdministrator bool   `json:"isAdministrator"`
	Email           string `json:"email"`
	Token           string `json:"token"`
}

LoginResult wraps the response of the login endpoint.

type ResponseError

type ResponseError struct {
	Code int
}

ResponseError is returned when a request returns an erroneous response code.

func (ResponseError) Error

func (err ResponseError) Error() string

type SplitSentenceResult

type SplitSentenceResult struct {
	SplittedTexts     [][]string  `json:"splitted_texts"`
	Lang              LangSpec    `json:"lang"`
	LangIsConfident   bool        `json:"lang_is_confident"`
	DetectedLanguages interface{} `json:"detectedLanguages"` // No clue what type this might be because only {} is always returned
}

SplitSentenceResult wraps the response of the spit sentence endpoint.

type Translation

type Translation struct {
	Beams   []*Beam `json:"beams"`
	Quality string  `json:"quality"`
}

Translation contains an array of beams for the translation as well as a quality identificator.

func (*Translation) Beam

func (t *Translation) Beam(i int) *Beam

Beam is a safe getter for a beam with the given index. If there is no entry at the given index, nil is returned.

type TranslationOptions

type TranslationOptions struct {
	Formality        Formality `json:"formality"`
	PreferedNumBeams int       `json:"prefered_num_beams"`
}

TranslationOptions wraps additional options for the translation endpoint.

type TranslationResult

type TranslationResult struct {
	Translations          []*Translation `json:"translations"`
	TargetLang            LangSpec       `json:"target_lang"`
	SourceLang            LangSpec       `json:"source_lang"`
	SourceLangIsConfident bool           `json:"source_lang_is_confident"`
	DetectedLanguages     interface{}    `json:"detectedLanguages"` // No clue what type this might be because only {} is always returned
}

TranslationResult wraps a translation response.

func (*TranslationResult) Assemble

func (tr *TranslationResult) Assemble() string

Assemble takes all sentences of a translation using the first beam of each translation and assembles them to one string.

func (*TranslationResult) Sentences

func (tr *TranslationResult) Sentences() []string

Sentences returns an array of the translated sentences using the first result beam of each sentence.

func (*TranslationResult) Translation

func (tr *TranslationResult) Translation(i int) *Translation

Translation is a safe getter for a translation with the given index. If there is no entry at the given index, nil is returned.

Directories

Path Synopsis
examples
pro

Jump to

Keyboard shortcuts

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