Files
fancy/fancy-backend/internal/provider/translation/deepl.go
T
Ivan Rezchikov 628dd6384b
Build and Deploy / test-backend (push) Successful in 1m11s
Build and Deploy / lint-frontend (push) Successful in 21s
Build and Deploy / build-backend (push) Successful in 58s
Build and Deploy / deploy (push) Canceled after 0s
Build and Deploy / build-frontend (push) Canceled after 5m38s
version 1
2026-09-18 00:45:51 +03:00

141 lines
3.7 KiB
Go

package translation
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"strings"
"time"
"github.com/dusiburg/fancy-api/internal/model"
)
const (
deeplTranslateAPIURL = "https://api-free.deepl.com/v2/translate"
deeplUsageAPIURL = "https://api-free.deepl.com/v2/usage"
deeplQuotaExceededStatus = 456
)
type DeepLProvider struct {
apiKey string
client *http.Client
}
func NewDeepLProvider(apiKey string) *DeepLProvider {
return &DeepLProvider{apiKey: apiKey, client: &http.Client{Timeout: 5 * time.Second}}
}
type deeplRequest struct {
Text []string `json:"text"`
SourceLang string `json:"source_lang"`
TargetLang string `json:"target_lang"`
}
type deeplResponse struct {
Translations []struct {
DetectedSourceLanguage string `json:"detected_source_language"`
Text string `json:"text"`
} `json:"translations"`
}
func (p *DeepLProvider) Translate(ctx context.Context, text string, from, to model.Language) (*model.TranslationResult, error) {
if _, ok := model.ParseLanguage(string(from)); !ok {
return nil, fmt.Errorf("%w: %s", ErrUnsupportedLanguage, from)
}
if _, ok := model.ParseLanguage(string(to)); !ok {
return nil, fmt.Errorf("%w: %s", ErrUnsupportedLanguage, to)
}
reqBody := deeplRequest{
Text: []string{text},
SourceLang: strings.ToUpper(string(from)),
TargetLang: strings.ToUpper(string(to)),
}
bodyBytes, err := json.Marshal(reqBody)
if err != nil {
return nil, fmt.Errorf("marshal request: %w", err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, deeplTranslateAPIURL, bytes.NewReader(bodyBytes))
if err != nil {
return nil, fmt.Errorf("build request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "DeepL-Auth-Key "+p.apiKey)
resp, err := p.client.Do(req)
if err != nil {
return nil, fmt.Errorf("deepl request failed: %w", err)
}
defer resp.Body.Close()
switch resp.StatusCode {
case http.StatusOK:
case http.StatusUnauthorized, http.StatusForbidden:
return nil, ErrAuthFailed
case http.StatusTooManyRequests, deeplQuotaExceededStatus:
return nil, ErrQuotaExceeded
default:
return nil, fmt.Errorf("unexpected status code: %d", resp.StatusCode)
}
var deeplResp deeplResponse
if err := json.NewDecoder(resp.Body).Decode(&deeplResp); err != nil {
return nil, fmt.Errorf("decode response: %w", err)
}
if len(deeplResp.Translations) == 0 {
return nil, fmt.Errorf("no translations returned")
}
translations := make([]string, 0, len(deeplResp.Translations))
for _, t := range deeplResp.Translations {
translations = append(translations, t.Text)
}
return &model.TranslationResult{
SourceText: text,
SourceLang: from,
TargetLang: to,
Translations: translations,
Provider: "DeepL",
}, nil
}
type deeplUsageResponse struct {
CharacterCount int64 `json:"character_count"`
CharacterLimit int64 `json:"character_limit"`
}
func (p *DeepLProvider) Usage(ctx context.Context) (*model.DeepLUsage, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, deeplUsageAPIURL, nil)
if err != nil {
return nil, fmt.Errorf("build request: %w", err)
}
req.Header.Set("Authorization", "DeepL-Auth-Key "+p.apiKey)
resp, err := p.client.Do(req)
if err != nil {
return nil, fmt.Errorf("deepl usage request failed: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("unexpected status code: %d", resp.StatusCode)
}
var payload deeplUsageResponse
if err := json.NewDecoder(resp.Body).Decode(&payload); err != nil {
return nil, fmt.Errorf("decode response: %w", err)
}
return &model.DeepLUsage{
CharacterCount: payload.CharacterCount,
CharacterLimit: payload.CharacterLimit,
}, nil
}