Translate to regional language variant (e.g. pt-BR) (#32428)

This commit is contained in:
Christian Schmidt 2024-10-15 14:26:20 +01:00 committed by Claire
parent dc2f9eef77
commit 0ff427fab3
3 changed files with 21 additions and 4 deletions

View File

@ -23,6 +23,6 @@ class Api::V1::Statuses::TranslationsController < Api::V1::Statuses::BaseControl
private
def set_translation
@translation = TranslateStatusService.new.call(@status, content_locale)
@translation = TranslateStatusService.new.call(@status, I18n.locale.to_s)
end
end

View File

@ -9,6 +9,8 @@ class TranslateStatusService < BaseService
def call(status, target_language)
@status = status
@source_texts = source_texts
target_language = target_language.split(/[_-]/).first unless target_languages.include?(target_language)
@target_language = target_language
raise Mastodon::NotPermittedError unless permitted?
@ -32,11 +34,15 @@ class TranslateStatusService < BaseService
def permitted?
return false unless @status.distributable? && TranslationService.configured?
languages[@status.language]&.include?(@target_language)
target_languages.include?(@target_language)
end
def languages
Rails.cache.fetch('translation_service/languages', expires_in: 7.days, race_condition_ttl: 1.hour) { TranslationService.configured.languages }
Rails.cache.fetch('translation_service/languages', expires_in: 7.days, race_condition_ttl: 1.hour) { translation_backend.languages }
end
def target_languages
languages[@status.language] || []
end
def content_hash

View File

@ -18,7 +18,7 @@ RSpec.describe TranslateStatusService do
describe '#call' do
before do
translation_service = TranslationService.new
allow(translation_service).to receive(:languages).and_return({ 'en' => ['es'] })
allow(translation_service).to receive(:languages).and_return({ 'en' => ['es', 'es-MX'] })
allow(translation_service).to receive(:translate) do |texts|
texts.map do |text|
TranslationService::Translation.new(
@ -37,6 +37,7 @@ RSpec.describe TranslateStatusService do
.to have_attributes(
content: '<p>Hola</p>',
detected_source_language: 'en',
language: 'es',
provider: 'Dummy',
status: status
)
@ -101,6 +102,16 @@ RSpec.describe TranslateStatusService do
expect(media_attachment.description).to eq 'Hola & :highfive:'
end
end
describe 'target language is regional' do
it 'uses regional variant' do
expect(service.call(status, 'es-MX').language).to eq 'es-MX'
end
it 'uses parent locale for unsupported regional variant' do
expect(service.call(status, 'es-XX').language).to eq 'es'
end
end
end
describe '#source_texts' do