PHP: Übersetzung mit DeepL

2018-04-22 00:00:00 IN1 , 2023-04-13 16:18:57 IN1


Es gibt bei DeepL Translator eine freie API welche für Anfragen verwendet werden kann. Hierzu ist kein Schlüssel o.ä und auch keine Registrierung notwendig.

Limitierungen

Character Limit

Laut DeepL.com ist die Länge des zu übersetzenden Textes auf 5000 Zeichen begrenzt.

Request Limit

Es ist nicht klar, inwieweit die API hinsichtlich der Häufigkeit von Anfragen beschränkt ist, bzw.: Es gibt ein Limit, dieses ist jedoch nicht bekannt.

PHP Script

Es gibt u.a. bei github mit DeepLy ein Projekt, welches um ein Vielfaches umfangreicher und besser ist als die folgende Klasse jemals sein kann. Es soll auch mit dieser simplen Klasse primär veranschaulicht werden, dass eine Translation mittels DeepL überhaupt möglich ist - und es geht mir um Nachvollziehbarkeit; Denn die wesentlichen Dinge für eine erfolgreiche Überstezung sind hier implementiert.

Verwendung

<?php

$oDeepl = new Deepl();

$sTranslation = $oDeepl->getTranslation(
    "Hallo Fulvio, ich grüße Dich. Dies ist eine Übersetzung mithilfe von DeepL.",
    "IT",   // to
    "DE"    // from
);

// Ciao Fulvio, ti saluto, questa è una traduzione che utilizza DeepL.
echo $sTranslation;

PHP Klasse

class Deepl
{
    /**
     * Amount of Characters per Request is limited by DeepL
     * @var integer
     */
    const CHARACTER_LIMIT = 5000;

    /**
     * Available Languages
     * @var array
     * @access protected
     */
    protected $aLangAvailable = [
        "auto" => "Auto detect",
        "DE" => "German",
        "EN" => "English",
        "FR" => "French",
        "ES" => "Spanish",
        "IT" => "Italian",
        "NL" => "Dutch",
        "PL" => "Polish"
    ];

    /**
     * @var array
     * @access protected
     */
    protected $aConfig = [
        "jsonrpc" => "2.0",
        "method" => "LMT_handle_jobs",
        "params" => [
            "jobs" => [
                [
                    "kind" => "default",
                    "raw_en_sentence" => ""
                ]
            ],
            "lang" => [
                "user_preferred_langs" => [
                    "DE",
                    "EN"
                ],
                "source_lang_user_selected" => "DE",
                "target_lang" => "EN"
            ],
            "priority" => -1
        ]
    ];

    public function __construct(array $aConfig = array())
    {
        if (!empty($aConfig))
        {
            $this->aConfig = $aConfig;
        }
    }

    protected function setText($sText = '')
    {
        if (strlen($sText) > self::$CHARACTER_LIMIT)
        {
            return false;
        }

        $this->aConfig['params']['jobs'][0]['raw_en_sentence'] = $sText;

        return true;
    }

    protected function setFromTo($sFrom = 'DE', $sTo = 'EN')
    {
        if (!in_array($sFrom, $this->aLangAvailable))
        {
            $sFrom = 'auto';
        }

        if (!in_array($sTo, $this->aLangAvailable))
        {
            $sTo = 'EN';
        }

        if ($sFrom == $sTo)
        {
            return false;
        }

        $this->aConfig['params']['lang']['user_preferred_langs'] = [$sFrom, $sTo];
        $this->aConfig['params']['lang']['source_lang_user_selected'] = $sFrom;
        $this->aConfig['params']['lang']['target_lang'] = $sTo;

        return true;
    }

    public function getTranslation($sText = '', $sTo = 'EN', $sFrom = 'auto')
    {
        if  (
                    (('' === $sText || empty($sText)) || ('' === $sFrom || empty($sFrom)) || ('' === $sTo || empty($sTo)))
                ||  (false === $this->setText($sText))
                ||  (false === $this->setFromTo($sFrom, $sTo))
            )
        {
            return '';
        }

        $sResponse = file_get_contents(

            'https://www.deepl.com/jsonrpc'
            , false
            , stream_context_create(array(

                // formulate a request via http/Post
                'http' => array(
                    'header'  => "Content-type: application/x-www-form-urlencoded\r\n"
                    ,'method'  => 'POST'
                    ,'content' => json_encode($this->aConfig),
                )
            )
        ));

        $aResponse = json_decode(
            $sResponse, 
            true
        );

        return $aResponse['result']['translations'][0]['beams'][0]['postprocessed_sentence'];
    }
}

Links

This website uses Cookies to provide you with the best possible service. Please see our Privacy Policy for more information. Click the check box below to accept cookies. Then confirm with a click on "Save".