discourse/plugins/discourse-ai/lib/translation/topic_localizer.rb
Natalie Tay 675a5e5be3
DEV: Add rake task to backfill localization excerpts which were empty (#36901)
This is a continuation of
https://github.com/discourse/discourse/pull/36885.

The rake task here backfills `topic_localization.excerpt` which may have
been empty (both `nil` and `""` are valid as checked on meta).

The reason why this can't be a migration is because we use
`Post.excerpt` which taps on a method in the post model which also uses
`PrettyText`.
2025-12-30 17:04:36 +08:00

51 lines
1.4 KiB
Ruby
Vendored

# frozen_string_literal: true
module DiscourseAi
module Translation
class TopicLocalizer
include LocalizableQuota
def self.localize(
topic,
target_locale = I18n.locale,
topic_title_llm_model: nil,
post_raw_llm_model: nil
)
return if topic.blank? || target_locale.blank? || topic.locale == target_locale.to_s
target_locale = target_locale.to_s.sub("-", "_")
translated_title =
TopicTitleTranslator.new(
text: topic.title,
target_locale:,
topic:,
llm_model: topic_title_llm_model,
).translate
translated_excerpt = nil
translated_excerpt =
PostRawTranslator.new(
text: topic.excerpt,
target_locale:,
topic:,
llm_model: post_raw_llm_model,
).translate if topic.excerpt.present?
localization =
TopicLocalization.find_or_initialize_by(topic_id: topic.id, locale: target_locale)
localization.title = translated_title
localization.fancy_title = Topic.fancy_title(translated_title)
localization.excerpt = translated_excerpt
localization.localizer_user_id = Discourse.system_user.id
localization.save!
localization
end
def self.model_name
"topic"
end
end
end
end