discourse/plugins/discourse-ai/lib/translation/post_localizer.rb
Natalie Tay b7d7f99c04
FEATURE: Allow re-localization twice a day if post version has changed (#34023)
This commit is a continuation of
https://github.com/discourse/discourse-ai/pull/1422.

Previously, we entirely skipped / disallowed localization. With this PR,
- For topics, we will only enqueue the translate title job if the post
revisor indicates there is a title change
- For posts, we will only enqueue the translate post job if there is a
post version change

Both jobs will be enqueued with a delay of
`SiteSetting.editing_grace_period` or `5 minutes`, whichever is larger.
Each topic or post may be retranslated to a locale at a maximum of twice
a day.
2025-08-04 10:58:30 +08:00

57 lines
1.8 KiB
Ruby
Vendored

# frozen_string_literal: true
module DiscourseAi
module Translation
class PostLocalizer
def self.localize(post, target_locale = I18n.locale)
if post.blank? || target_locale.blank? ||
LocaleNormalizer.is_same?(post.locale, target_locale) || post.raw.blank?
return
end
return if post.raw.length > SiteSetting.ai_translation_max_post_length
target_locale = target_locale.to_s.sub("-", "_")
translated_raw = PostRawTranslator.new(text: post.raw, target_locale:, post:).translate
localization =
PostLocalization.find_or_initialize_by(post_id: post.id, locale: target_locale)
localization.raw = translated_raw
localization.cooked = PrettyText.cook(translated_raw)
localization.post_version = post.version
localization.localizer_user_id = Discourse.system_user.id
localization.save!
localization
end
def self.has_relocalize_quota?(post, locale, skip_incr: false)
return false if get_relocalize_quota(post, locale).to_i >= 2
incr_relocalize_quota(post, locale) unless skip_incr
true
end
private
def self.relocalize_key(post, locale)
"post_relocalized_#{post.id}_#{locale}"
end
def self.get_relocalize_quota(post, locale)
Discourse.redis.get(relocalize_key(post, locale)).to_i || 0
end
def self.incr_relocalize_quota(post, locale)
key = relocalize_key(post, locale)
if (count = get_relocalize_quota(post, locale)).zero?
Discourse.redis.set(key, 1, ex: 1.day.to_i)
else
ttl = Discourse.redis.ttl(key)
incr = count.to_i + 1
Discourse.redis.set(key, incr, ex: ttl)
end
end
end
end
end