Suggerimenti automatici

Cambiato nella versione 4.13: Prima di Weblate 4.13, i servizi erano configurati nel file Configurazione.

The support for several machine translation and translation memory services is built-in. Each service can be turned on by the administrator for whole site (under Automatic suggestions in Management interface) or at the project settings:

../_images/project-machinery.webp

Nota

They come subject to their terms of use, so ensure you are allowed to use them how you want. Third-party services can receive source strings, translations, and related context from Weblate.

I servizi traducono dalla lingua sorgente come configurato in Component configuration vedere Lingua di origine.

Per-project automatic suggestion can also be configured via the API REST di Weblate.

Priorità ai servizi di traduzione automatica e di memorie di traduzione

Weblate Translation Memory matches with 100% score take priority over machine translation services. If 100% match in translation memory is found, no machine translation is performed. If several 100% matches occur, the first one returned by the database is used.

Each machine translation service has a predefined maximum score it can produce. The use of installed translation services is ordered according to their maximum score. For each string with translation score lower than the service’s maximum, the service is asked to produce a translation. Translations with a score exceeding the current one are accepted.

Stringhe di origine per la traduzione automatica

Added in version 5.11.

The origin of source strings for all third-party services can be configured. This can be used to tweak the service to get the best results. Following choices are available:

Selezione automatica

Chooses the best source language automatically.

Questo è il comportamento predefinito.

Lingua sorgente del componente

Utilizza la lingua sorgente dei componenti.

This was the behavior before the 5.11 release.

Lingua secondaria definita nel progetto o nel componente

Usa progetto Lingua secondaria o componente Lingua secondaria.

Falls back to the automatic selection of the source language if the secondary language not configured.

LLM translation context

LLM-based automatic suggestion services receive additional context about each translated string, when available. This includes the string context or monolingual key, additional explanation, configured secondary-language translation, plural information, failing quality checks, and placeholder contents. Matching glossary entries are passed with their explanations and selected flags, so duplicate glossary terms can be disambiguated.

You can add target-language-specific instructions in Language-specific instructions using a JSON object mapping language codes to text. Language codes have to exist in Weblate and are matched exactly; whitespace is not ignored. Each instruction can contain up to 1000 characters. Weblate first looks for the exact target language code and then falls back to the base language code.

The added metadata is used only to guide the generated suggestion; the returned translation still has to preserve the source placeholders and markup. Weblate also sends a short previous chat exchange to LLM services to demonstrate the expected JSON response format. The exchange uses bundled translated examples when available for the source and target language pair, or language-neutral formatting examples otherwise. Existing translations for the same target language can be appended as additional examples.

Alibaba

Added in version 5.3.

ID servizio:

alibaba

Maximal score:

80

Configurazione:

source_language

Selezione lingua sorgente

Scelte disponibili:

auto – Selezione automatica

source – Linguaggio di origine del componente

secondary – Lingua secondaria definita nel progetto o nel componente

key

ID chiave accesso

secret

Accesso alla chiave segreta

region

ID regione

Alibaba Translate is a neural machine translation service for translating text and it supports up to 214 language pairs.

Anthropic

Added in version 5.16.

ID servizio:

anthropic

Maximal score:

90

Funzionalità avanzate:
Configurazione:

source_language

Selezione lingua sorgente

Scelte disponibili:

auto – Selezione automatica

source – Linguaggio di origine del componente

secondary – Lingua secondaria definita nel progetto o nel componente

base_url

URL API di Anthropic

URL di base dell’API Anthropic. Lascia vuoto per utilizzare l’URL predefinito.

model

Modello di Anthropic

Scelte disponibili:

claude-haiku-4-5 – Claude Haiku 4.5

claude-sonnet-5 – Claude Sonnet 5

claude-opus-4-8 – Claude Opus 4.8

claude-fable-5 – Claude Fable 5

custom – Modello personalizzato

persona

Profilo traduttore

Per migliorare l’accuratezza della traduzione descrivi il profilo del traduttore. Ad esempio: «Sono un allevatore di scoiattoli.»

style

Stile traduttore

Descrivi lo stile della traduzione. Ad esempio: “Usa un linguaggio informale.”

language_instructions

Language-specific instructions

JSON object mapping existing target language codes to extra instructions, up to 1000 characters each.

key

Chiave API

custom_model

Nome del modello personalizzato

Necessario solo quando il modello è impostato su «Modello personalizzato»

max_tokens

Numero massimo di token

Numero massimo di token da generare nella risposta.

Esegue la traduzione utilizzando i modelli Anthropic’s Claude.

The Anthropic API provides access to the Claude family of models, which are known for their strong reasoning and language capabilities. You need an API key from Anthropic to use this service.

Use persona and style fields to further fine-tune translations. These will be used in a prompt for Claude and allow you to change the style of the translations.

The service automatically uses Glossario, see Glossari nel suggerimento automatico.

Apertium APy

ID servizio:

apertium-apy

Maximal score:

88

Configurazione:

source_language

Selezione lingua sorgente

Scelte disponibili:

auto – Selezione automatica

source – Linguaggio di origine del componente

secondary – Lingua secondaria definita nel progetto o nel componente

url

URL API

A libre software machine translation platform providing translations to a limited set of languages.

The recommended way to use Apertium is to run your own Apertium-APy server.

Amazon Translate

ID servizio:

aws

Maximal score:

88

Funzionalità avanzate:
Configurazione:

source_language

Selezione lingua sorgente

Scelte disponibili:

auto – Selezione automatica

source – Linguaggio di origine del componente

secondary – Lingua secondaria definita nel progetto o nel componente

key

ID chiave accesso

secret

Chiave segreta API

region

Nome regione

formality

Formalità

Scelte disponibili:

empty value – Default

FORMAL – Formal

INFORMAL – Informal

brevity

Brevity

Prefer shorter translations when supported.

Scelte disponibili:

empty value – Default

ON – Enabled

profanity

Profanity

Mask profane words in translated text.

Scelte disponibili:

empty value – Default

MASK – Mask profanity

Amazon Translate is a neural machine translation service for translating text to and from English across a breadth of supported languages. The service requires the TranslateFullAccess Managed Policy.

The service automatically uses Glossario, see Glossari nel suggerimento automatico.

Azure OpenAI

Added in version 5.8.

ID servizio:

azure-openai

Maximal score:

90

Funzionalità avanzate:
Configurazione:

source_language

Selezione lingua sorgente

Scelte disponibili:

auto – Selezione automatica

source – Linguaggio di origine del componente

secondary – Lingua secondaria definita nel progetto o nel componente

base_url

URL API

model

Modello LLM

persona

Profilo traduttore

Per migliorare l’accuratezza della traduzione descrivi il profilo del traduttore. Ad esempio: «Sono un allevatore di scoiattoli.»

style

Stile traduttore

Descrivi lo stile della traduzione. Ad esempio: “Usa un linguaggio informale.”

language_instructions

Language-specific instructions

JSON object mapping existing target language codes to extra instructions, up to 1000 characters each.

key

Chiave API

azure_endpoint

URL endpoint Azure OpenAI

URL dell’endpoint dell’istanza, ad esempio: https://my-instance.openai.azure.com.

deployment

Distribuzione di Azure OpenAI

Nome di distribuzione univoco del modello.

Esegue la traduzione utilizzando OpenAI ospitato su Azure.

Vedi anche

OpenAI

Baidu

ID servizio:

baidu

Maximal score:

90

Configurazione:

source_language

Selezione lingua sorgente

Scelte disponibili:

auto – Selezione automatica

source – Linguaggio di origine del componente

secondary – Lingua secondaria definita nel progetto o nel componente

key

ID client

secret

Segreto client

Machine translation service provided by Baidu.

This service uses an API and you need to obtain an ID and API key from Baidu to use it.

Vedi anche

Baidu Translate API

CyrTranslit

Added in version 5.7.

ID servizio:

cyrtranslit

Maximal score:

100

Configurazione:

source_language

Selezione lingua sorgente

Scelte disponibili:

auto – Selezione automatica

source – Linguaggio di origine del componente

secondary – Lingua secondaria definita nel progetto o nel componente

Servizio di traduzione automatica con la libreria Cyrtranslit.

This service converts text between Cyrillic and Latin scripts for languages that have both scripts.

DeepL

ID servizio:

deepl

Maximal score:

91

Funzionalità avanzate:
Configurazione:

source_language

Selezione lingua sorgente

Scelte disponibili:

auto – Selezione automatica

source – Linguaggio di origine del componente

secondary – Lingua secondaria definita nel progetto o nel componente

url

URL API

key

Chiave API

formality

Formalità

Se la lingua non è specificata come (in)formale usa la formalità specificata

context

Contesto di traduzione

Descrivi il contesto della traduzione per migliorare la precisione della traduzione.

next_gen

Usa il modello di nuova generazione

Preferisci l’LLM di nuova generazione al modello classico di traduzione automatica.

DeepL is a paid service providing good machine translation for a few languages. You need to purchase DeepL API subscription.

API URL to use with the DeepL service. Configure the base endpoint without an API version; Weblate selects the appropriate DeepL API version for each request.

Cambiato nella versione 2026.7: DeepL API v1 is no longer supported.

https://api.deepl.com/ (default in Weblate)

Is meant for API usage on the paid plan, and the subscription is usage-based.

https://api-free.deepl.com/

Is meant for API usage on the free plan, and the subscription is usage-based.

Weblate supports DeepL formality, it will choose matching one based on the language (for example, there is de@formal and de@informal).

The translation context can optionally be specified to improve translations quality. Read more on that in DeepL translation context documentation.

The service automatically uses Glossario, see Glossari nel suggerimento automatico.

Glosbe

ID servizio:

glosbe

Maximal score:

90

Configurazione:

source_language

Selezione lingua sorgente

Scelte disponibili:

auto – Selezione automatica

source – Linguaggio di origine del componente

secondary – Lingua secondaria definita nel progetto o nel componente

Free dictionary and translation memory for almost every living language.

The API is gratis to use, but usage of the translations is subject to the license of the used data source. There is a limit of calls that may be done from one IP in a set period of time, to prevent abuse.

Vedi anche

Glosbe website

Google Cloud Translation Basic

ID servizio:

google-translate

Maximal score:

90

Configurazione:

source_language

Selezione lingua sorgente

Scelte disponibili:

auto – Selezione automatica

source – Linguaggio di origine del componente

secondary – Lingua secondaria definita nel progetto o nel componente

key

Chiave API

Traduzione automatica fornito dai servizi Google Cloud.

This service uses the Google Translation API v2, and you need to obtain an API key and turn on billing in the Google API console.

Google Cloud Translation Advanced

ID servizio:

google-translate-api-v3

Maximal score:

90

Funzionalità avanzate:
Configurazione:

source_language

Selezione lingua sorgente

Scelte disponibili:

auto – Selezione automatica

source – Linguaggio di origine del componente

secondary – Lingua secondaria definita nel progetto o nel componente

credentials

Informazioni account servizio Google Translate

Inserisci una chiave JSON per l’account di servizio.

project

Progetto Google Translate

Inserisci l’ID numerico/alfanumerico del progetto Google Cloud.

location

Posizione Google Translate

Scegli una regione Google Cloud Translation da usare per il progetto Google Cloud o la regione più vicina a te.

bucket_name

Nome bucket di Google Storage

Inserisci il nome del bucket Google Cloud Storage usato per archiviare i file del glossario.

Traduzione automatica fornito dai servizi Google Cloud.

This service uses the Google Translation API v3 and you need credentials in JSON format to access it.

In order to use this service, you first need to go through the following steps:

  1. Select or create a Cloud Platform project.

  2. Enable billing for your project.

  3. Enable the Cloud Translation.

  4. Setup Authentication.

Optionally, you can configure the service to use Glossario by setting up a Bucket:

  1. Create a Google Cloud bucket.

  2. Set bucket location to «us-central1».

  3. Grant “Storage Admin” permission to the Service Account.

Traduttore linguistico IBM Watson

Removed in version 5.13.1: This service was withdrawn by vendor as of 10 December 2024.

LibreTranslate

Added in version 4.7.1.

ID servizio:

libretranslate

Maximal score:

89

Configurazione:

source_language

Selezione lingua sorgente

Scelte disponibili:

auto – Selezione automatica

source – Linguaggio di origine del componente

secondary – Lingua secondaria definita nel progetto o nel componente

url

URL API

key

Chiave API

LibreTranslate is a free and open-source service for machine translations. The public instance requires an API key, but LibreTranslate can be self-hosted and there are several mirrors available to use the API for free.

https://libretranslate.com/ (official public instance)

Requires an API key to use outside of the website.

LTEngine

Added in version 5.17.1.

ID servizio:

ltengine

Maximal score:

89

Configurazione:

source_language

Selezione lingua sorgente

Scelte disponibili:

auto – Selezione automatica

source – Linguaggio di origine del componente

secondary – Lingua secondaria definita nel progetto o nel componente

url

URL API

key

Chiave API

LTEngine provides a local LibreTranslate-compatible API backed by large language models. For many Weblate installations, native LLM services such as Ollama can be a better fit because Weblate can send translation context directly to the model. Use LTEngine when you specifically want its local translation engine or future LTEngine translation improvements.

Azure AI Translator

ID servizio:

microsoft-translator

Maximal score:

90

Funzionalità avanzate:
Configurazione:

source_language

Selezione lingua sorgente

Scelte disponibili:

auto – Selezione automatica

source – Linguaggio di origine del componente

secondary – Lingua secondaria definita nel progetto o nel componente

key

Chiave API

base_url

URL base applicazione

Scelte disponibili:

api.cognitive.microsofttranslator.com – Global (non-regional)

api-apc.cognitive.microsofttranslator.com – Asia Pacific

api-eur.cognitive.microsofttranslator.com – Europe

api-nam.cognitive.microsofttranslator.com – North America

api.translator.azure.cn – China

api.cognitive.microsofttranslator.us – Azure US Government cloud

endpoint_url

URL server autenticazione

Può essere specificato «Regionale» o «Multiservizio» usando il campo regione sottostante.

Scelte disponibili:

api.cognitive.microsoft.com – Global

api.cognitive.azure.cn – China

api.cognitive.microsoft.us – Azure US Government cloud

region

Regione servizio autenticazione

category

Categoria

Specifica un ID di categoria di sistema personalizzato da usare al posto di quello generale.

Machine translation service provided by Microsoft in Azure portal as one of Cognitive Services.

Weblate implements Translator API V3.

The service automatically uses Glossario via dynamic dictionary, see Glossari nel suggerimento automatico.

Translator Text API V2

The key you use with Translator API V2 can be used with API 3.

Translator Text API V3

You need to register at Azure portal and use the key you obtain there. With new Azure keys, you also need to set region to locale of your service.

You can also specify a custom category to use custom translator.

Suggerimento

For Azure China, please use your endpoint from the Azure Portal.

Mistral

Added in version 2026.7.

ID servizio:

mistral

Maximal score:

90

Funzionalità avanzate:
Configurazione:

source_language

Selezione lingua sorgente

Scelte disponibili:

auto – Selezione automatica

source – Linguaggio di origine del componente

secondary – Lingua secondaria definita nel progetto o nel componente

base_url

Mistral API base URL

Base URL of the Mistral API, if it differs from the Mistral default URL

model

Mistral model

Scelte disponibili:

auto – Selezione automatica

ministral-3b-latest – Ministral 3 3B

ministral-8b-latest – Ministral 3 8B

mistral-small-latest – Mistral Small 4

ministral-14b-latest – Ministral 3 14B

mistral-large-latest – Mistral Large 3

mistral-medium-latest – Mistral Medium 3.5

custom – Modello personalizzato

persona

Profilo traduttore

Per migliorare l’accuratezza della traduzione descrivi il profilo del traduttore. Ad esempio: «Sono un allevatore di scoiattoli.»

style

Stile traduttore

Descrivi lo stile della traduzione. Ad esempio: “Usa un linguaggio informale.”

language_instructions

Language-specific instructions

JSON object mapping existing target language codes to extra instructions, up to 1000 characters each.

key

Chiave API

custom_model

Nome del modello personalizzato

Necessario solo quando il modello è impostato su «Modello personalizzato»

ModernMT

Added in version 4.2.

ID servizio:

modernmt

Maximal score:

90

Funzionalità avanzate:
Configurazione:

source_language

Selezione lingua sorgente

Scelte disponibili:

auto – Selezione automatica

source – Linguaggio di origine del componente

secondary – Lingua secondaria definita nel progetto o nel componente

url

URL API

key

Chiave API

context_vector

Vettore di contesto

Elenco, separato da virgole, di identificativi di memoria seguiti dal loro peso (ID:peso). Esempio 1234:0.123,4567:0.456

The service automatically uses Glossario, see Glossari nel suggerimento automatico.

Vedi anche

ModernMT API

MyMemory

ID servizio:

mymemory

Maximal score:

100

Configurazione:

source_language

Selezione lingua sorgente

Scelte disponibili:

auto – Selezione automatica

source – Linguaggio di origine del componente

secondary – Lingua secondaria definita nel progetto o nel componente

email

E-mail contatto

username

Nome utente

key

Chiave API

Huge translation memory with machine translation.

Free, anonymous usage is currently limited to 100 requests/day, or to 1000 requests/day when you provide a contact e-mail address in email. You can also ask them for more.

Vedi anche

MyMemory website

Netease Sight

ID servizio:

netease-sight

Maximal score:

90

Configurazione:

source_language

Selezione lingua sorgente

Scelte disponibili:

auto – Selezione automatica

source – Linguaggio di origine del componente

secondary – Lingua secondaria definita nel progetto o nel componente

key

ID client

secret

Segreto client

Traduzione automatica fornita da NetEase.

This service uses an API, and you need to obtain key and secret from NetEase.

Ollama

Added in version 5.15.

ID servizio:

ollama

Maximal score:

90

Funzionalità avanzate:
Configurazione:

source_language

Selezione lingua sorgente

Scelte disponibili:

auto – Selezione automatica

source – Linguaggio di origine del componente

secondary – Lingua secondaria definita nel progetto o nel componente

base_url

URL API

URL di base dell’API Ollama, localhost e porta 11434 per impostazione predefinita.

model

Modello Ollama

Nome del modello descritto nel catalogo Ollama.

persona

Profilo traduttore

Per migliorare l’accuratezza della traduzione descrivi il profilo del traduttore. Ad esempio: «Sono un allevatore di scoiattoli.»

style

Stile traduttore

Descrivi lo stile della traduzione. Ad esempio: “Usa un linguaggio informale.”

language_instructions

Language-specific instructions

JSON object mapping existing target language codes to extra instructions, up to 1000 characters each.

Esegue la traduzione utilizzando i modelli Ollama.

The Ollama API allows for the use of open source models for translations either locally installed or remotely accessed via the Ollama service. Note that before configuring your models, you should have Ollama installed and downloaded the models you wish to use.

Use persona and style fields to further fine-tune translations. These will be used in a prompt for Ollama and allow you to change the style of the translations.

The service automatically uses Glossario, see Glossari nel suggerimento automatico.

Vedi anche

OpenAI

Added in version 5.3.

ID servizio:

openai

Maximal score:

90

Funzionalità avanzate:
Configurazione:

source_language

Selezione lingua sorgente

Scelte disponibili:

auto – Selezione automatica

source – Linguaggio di origine del componente

secondary – Lingua secondaria definita nel progetto o nel componente

base_url

URL di base API OpenAI

URL di base dell’API OpenAI, se diverso dall’URL predefinito di OpenAI

model

Modello OpenAI

Scelte disponibili:

auto – Selezione automatica

gpt-5-nano – GPT-5 nano

gpt-5.4-nano – GPT-5.4 nano

gpt-5-mini – GPT-5 mini

gpt-5.4-mini – GPT-5.4 mini

gpt-5.6-luna – GPT-5.6 Luna

gpt-5 – GPT-5

gpt-5.4 – GPT-5.4

gpt-5.6-terra – GPT-5.6 Terra

gpt-5.5 – GPT-5.5

gpt-5.6 – GPT-5.6 Sol

custom – Modello personalizzato

persona

Profilo traduttore

Per migliorare l’accuratezza della traduzione descrivi il profilo del traduttore. Ad esempio: «Sono un allevatore di scoiattoli.»

style

Stile traduttore

Descrivi lo stile della traduzione. Ad esempio: “Usa un linguaggio informale.”

language_instructions

Language-specific instructions

JSON object mapping existing target language codes to extra instructions, up to 1000 characters each.

key

Chiave API

custom_model

Nome del modello personalizzato

Necessario solo quando il modello è impostato su «Modello personalizzato»

Esegue la traduzione utilizzando OpenAI.

The OpenAI API is powered by a diverse set of models with different capabilities and price points. Automatic selection chooses the best model available, but you might want to choose a specific model that matches your needs.

Use persona and style fields to further fine-tune translations. These will be used in a prompt for OpenAI and allow you to change the style of the translations.

The service automatically uses Glossario, see Glossari nel suggerimento automatico.

Cambiato nella versione 5.7: Support for custom model and base URL was added.

SAP Translation Hub

ID servizio:

sap-translation-hub

Maximal score:

100

Configurazione:

source_language

Selezione lingua sorgente

Scelte disponibili:

auto – Selezione automatica

source – Linguaggio di origine del componente

secondary – Lingua secondaria definita nel progetto o nel componente

url

URL API

key

Chiave API

username

Nome utente SAP

password

Password SAP

enable_mt

Abilita traduzione automatica

domain

Dominio traduzione

L’ID di un dominio traduzione, ad esempio BC. Se non specifichi un dominio, verranno cercate le traduzioni in tutti i domini disponibili.

Machine translation service provided by SAP.

You need to have a SAP account (and the SAP Translation Hub enabled in the SAP Cloud Platform) to use this service.

You can also configure whether to also use machine translation services, in addition to the term database.

Nota

To access the Sandbox API, you need to set url and key.

To access the productive API, you need to set url, username and password.

Systran

ID servizio:

systran

Maximal score:

90

Configurazione:

source_language

Selezione lingua sorgente

Scelte disponibili:

auto – Selezione automatica

source – Linguaggio di origine del componente

secondary – Lingua secondaria definita nel progetto o nel componente

key

Chiave API

Traduzione automatica fornita da Systran.

This service uses an API, and you need to obtain API key at <https://translate.systran.net/en/account>.

tmserver

ID servizio:

tmserver

Maximal score:

100

Configurazione:

source_language

Selezione lingua sorgente

Scelte disponibili:

auto – Selezione automatica

source – Linguaggio di origine del componente

secondary – Lingua secondaria definita nel progetto o nel componente

url

URL API

You can run your own translation memory server by using a tmserver protocol.

  • The original tmserver was bundled with the translate-toolkit.

  • amaGama server is an enhanced version of tmserver.

Nota

There currently does not seem to be a maintained server for this.

Weblate

ID servizio:

weblate

Maximal score:

100

Configurazione:

This service has no configuration.

Weblate machine translation service can provide translations based on the exact matches of a string in the currently existing strings in a Translated, Approved, or Read-only states inside Weblate.

Weblate Translation Memory

ID servizio:

weblate-translation-memory

Maximal score:

100

Configurazione:

This service has no configuration.

Use Memoria traduzione as a machine translation service. Any string that has been translated before (or uploaded to the translation memory) can be translated in this way. This suggestion source works with fuzzy matching.

Nota

Recreating Memoria traduzione reduces capabilities of this TM source.

Yandex

ID servizio:

yandex

Maximal score:

90

Configurazione:

source_language

Selezione lingua sorgente

Scelte disponibili:

auto – Selezione automatica

source – Linguaggio di origine del componente

secondary – Lingua secondaria definita nel progetto o nel componente

key

Chiave API

Machine translation service provided by Yandex.

This service uses a Translation API, and you need to obtain an API key from Yandex.

Yandex v2

Added in version 5.1.

ID servizio:

yandex-v2

Maximal score:

90

Configurazione:

source_language

Selezione lingua sorgente

Scelte disponibili:

auto – Selezione automatica

source – Linguaggio di origine del componente

secondary – Lingua secondaria definita nel progetto o nel componente

key

Chiave API

Machine translation service provided by Yandex.

This service uses a Translation API, and you need to obtain an API key from Yandex Cloud.

Youdao Zhiyun

ID servizio:

youdao-zhiyun

Maximal score:

90

Configurazione:

source_language

Selezione lingua sorgente

Scelte disponibili:

auto – Selezione automatica

source – Linguaggio di origine del componente

secondary – Lingua secondaria definita nel progetto o nel componente

key

ID client

secret

Segreto client

Machine translation service provided by Youdao.

This service uses an API, and you need to obtain an ID and an API key from Youdao.

Custom machine translation

You can also implement your own machine translation services using a few lines of Python code. Place the code in a module Weblate can import (see Creating a Python module or Codice di personalizzazione) and add fully qualified class name to WEBLATE_MACHINERY.

"""
Machine translation example.

This example uses fictional http://example.com/ service to translate the
strings.
"""

from __future__ import annotations

from typing import TYPE_CHECKING

from weblate.machinery.base import MACHINERY_DEFAULT_THRESHOLD, MachineTranslation

if TYPE_CHECKING:
    from weblate.auth.models import User
    from weblate.machinery.base import DownloadTranslations
    from weblate.trans.models import Unit


class SampleTranslation(MachineTranslation):
    """Sample machine translation interface."""

    name = "Sample"

    def download_languages(self):
        """Return list of languages your machine translation supports."""
        response = self.request("get", "http://example.com/languages")
        return response.json()["languages"]

    def download_translations(
        self,
        source_language,
        target_language,
        text: str,
        unit: Unit | None,
        user: User | None,
        threshold: int = MACHINERY_DEFAULT_THRESHOLD,
    ) -> DownloadTranslations:
        """Return tuple with translations."""
        response = self.request(
            "get",
            "http://example.com/translate",
            params={
                "source_language": source_language,
                "target_language": target_language,
                "text": text,
            },
        )

        for translation in response.json()["translations"]:
            yield {
                "text": translation,
                "quality": 100,
                "service": self.name,
                "source": text,
            }