translator

package module
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Aug 4, 2023 License: MIT Imports: 12 Imported by: 1

README

Translator

Go Reference

A Golang library that provides translation and language detection using the Google Translate API. It is a fork of the go-googletrans library with added functionalities for language detection, default service URLs, and available languages.

Installation

To use the translator library in your Go project, you need to install it using go get:

go get github.com/lcapuano-app/go-googletrans

Usage

Here's a simple example of how to use the translator library:

package main

import (
	"fmt"
	translator "github.com/lcapuano-app/go-googletrans"
)

func main() {
	// Create a new instance of the Translator.
	t := translator.New()

	// Translate text from English to Spanish.
	originText := "Hello, how are you?"
	sourceLanguage := "en"
	destinationLanguage := "es"

	translated, err := t.Translate(originText, sourceLanguage, destinationLanguage)
	if err != nil {
		fmt.Println("Error:", err)
		return
	}

	fmt.Println("Source Language:", translated.Src)
	fmt.Println("Destination Language:", translated.Dest)
	fmt.Println("Original Text:", translated.Origin)
	fmt.Println("Translated Text:", translated.Text)

	// Detect the language of a given text.
	textToDetect := "¡Hola, cómo estás?"
	detected, err := t.DetectLanguage(textToDetect, destinationLanguage)
	if err != nil {
		fmt.Println("Error:", err)
		return
	}

	fmt.Println("Detected Language:", detected.Src)
	fmt.Println("Confidence:", detected.Confidence)
}

Configuration

You can also customize the Translator instance by providing configuration options using the Config struct. The available options are:

  • ServiceUrls: A list of service URLs to be used for making API requests. If not provided, default service URLs will be used.
  • UserAgent: A list of user agent strings used in the request headers. If not provided, a default user agent will be used.
  • Proxy: The proxy URL to be used for making API requests. It should be in the format "http://proxy.example.com:8080". If not provided, no proxy will be used.

Available Methods

The translator library provides the following methods:

  • Translate: Translates text from one language to another using the Google Translate API.
  • DetectLanguage: Detects the language of a given text using the Google Translate API.
  • GetValidLanguageKey: Validates and returns the corresponding valid language code for a given language.
  • GetDefaultServiceUrls: Returns the default service URLs used by the Translator.
  • GetAvailableLanguages: Returns a map of available languages supported by the Google Translate API.

Contribution

Contributions to the translator library are welcome! If you find any issues or have suggestions for improvement, feel free to open an issue or submit a pull request.

License

This library is licensed under the MIT License. See the LICENSE file for details.


Documentation

Index

Constants

This section is empty.

Variables

View Source
var ReTkk = regexp.MustCompile(`tkk:'(.+?)'`)

Functions

func GetDefaultServiceUrls

func GetDefaultServiceUrls() []string

func GetValidLanguageKey added in v0.0.3

func GetValidLanguageKey(lang string) (string, error)

GetValidLanguageKey is a method of the Translator struct that validates and returns the corresponding valid language key for a given language. It checks whether the provided language is a valid language code or language name in the 'languages' map.

Parameters: - lang: The language code or language name to be validated.

Returns: - string: The valid language code (key) corresponding to the provided language. - error: An error if the provided language is not a valid language code or language name in the 'languages' map.

Example Usage:

language := "es"
validLang, err := translator.GetValidLanguageKey(language)
if err != nil {
  fmt.Println("Error:", err)
  return
}
fmt.Println("Valid Language Code:", validLang)

func Token

func Token(host string, client *http.Client) *tokenAcquirer

Types

type Config

type Config struct {
	ServiceUrls []string
	UserAgent   []string
	Proxy       string
}

Config basic opts.

type LDResponse

type LDResponse struct {
	Sentences  []sentence  `json:"sentences"`
	Src        string      `json:"src,omitempty"`
	Spell      interface{} `json:"spell,omitempty"`
	Confidence float64     `json:"confidence,omitempty"`
	LdResult   LDResult    `json:"ld_result,omitempty"`
}

Language detection (LD) response

type LDResult

type LDResult struct {
	Srclangs            []string  `json:"srclangs,omitempty"`
	SrclangsConfidences []float64 `json:"srclangs_confidences,omitempty"`
	ExtendedSrclangs    []string  `json:"extended_srclangs,omitempty"`
}

Language detection (LD) result

type Translated

type Translated struct {
	Src    string // source language
	Dest   string // destination language
	Origin string // original text
	Text   string // translated text
}

Translated result object.

type Translator

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

func New

func New(config ...Config) *Translator

New is a function that creates a new instance of the Translator with the specified configuration. If no configuration is provided, default values are used.

Parameters: - config: Variadic parameter that accepts optional configurations for the Translator.

  • ServiceUrls: A slice of service URLs used for making API requests. If not provided, defaultServiceUrls will be used.
  • UserAgent: A slice of user agent strings used in the request headers. If not provided, defaultUserAgent will be used.
  • Proxy: The proxy URL to be used for making API requests. It should be in the format "http://proxy.example.com:8080". If not provided, no proxy will be used.

Returns: - *Translator: A new instance of the Translator with the specified configurations.

Example Usage:

config := Config{
  ServiceUrls: []string{"https://api.example.com/translate", "https://api.example.org/translate"},
  UserAgent:   []string{"MyApp/1.0", "MyOtherApp/2.0"},
  Proxy:       "http://proxy.example.com:8080",
}
translator := New(config)

func (*Translator) DetectLanguage

func (a *Translator) DetectLanguage(origin, dest string) (LDResponse, error)

DetectLanguage is a public method of the Translator struct that allows users to detect the language of a given text and obtain its translation.

Parameters: - origin: The language code or "auto" to automatically detect the language of the input text. - dest: The language code for the desired translation output. (e.g., "es" for Spanish, "fr" for French)

Returns: - LDResponse: The detected language and translated text as a result of the language detection. - error: An error if there is any issue with the language detection or HTTP request.

Example Usage:

translator := New()
originText := "Hello, how are you?"
destinationLanguage := "es"
detected, err := translator.DetectLanguage("auto", destinationLanguage)
if err != nil {
  fmt.Println("Error:", err)
  return
}
fmt.Println("Detected Language:", detected.Lang)
fmt.Println("Translated Text:", detected.Trans)

func (*Translator) GetAvaliableLanguages

func (a *Translator) GetAvaliableLanguages() map[string]string

func (*Translator) Translate

func (a *Translator) Translate(origin, src, dest string) (*Translated, error)

Translate is a public method of the Translator struct that allows users to translate text from one language to another using the Google Translate API.

Parameters: - origin: The text to be translated. - src: The language code of the source text. (e.g., "en" for English, "es" for Spanish) - dest: The language code for the desired translation output. (e.g., "es" for Spanish, "fr" for French)

Returns: - *Translated: A struct containing the translation result, including the source language, destination language, original text, and translated text. - error: An error if there is any issue with the translation or HTTP request.

Example Usage:

translator := NewTranslator("YOUR_API_KEY")
originText := "Hello, how are you?"
sourceLanguage := "en"
destinationLanguage := "es"
translated, err := translator.Translate(originText, sourceLanguage, destinationLanguage)
if err != nil {
  fmt.Println("Error:", err)
  return
}
fmt.Println("Source Language:", translated.Src)
fmt.Println("Destination Language:", translated.Dest)
fmt.Println("Original Text:", translated.Origin)
fmt.Println("Translated Text:", translated.Text)

Jump to

Keyboard shortcuts

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