discourse/plugins/discourse-ai/lib/translation/post_localizer.rb
Natalie Tay da70ebe7b5
FIX: Ensure upload reference is available before cooking (#36887)
We're seeing errors like the following due to the localization not being
`save` before post processing happens.

```
Post-processing failed for localization of post 1913030 to ja: ActiveRecord::NotNullViolation - PG::NotNullViolation: ERROR:  null value in column "target_id" of relation "upload_references" violates not-null constraint
DETAIL:  Failing row contains (5381685, 537219, PostLocalization, null, 2025-12-29 03:52:22.738494, 2025-12-29 03:52:22.738499).
```

This commit ensures the upload reference is created prior to post
processing.

/t/168872
2025-12-29 23:33:16 +08:00

46 lines
1.6 KiB
Ruby
Vendored

# frozen_string_literal: true
module DiscourseAi
module Translation
class PostLocalizer
include LocalizableQuota
def self.localize(post, target_locale = I18n.locale, llm_model: nil)
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:, llm_model:).translate
localization =
PostLocalization.find_or_initialize_by(post_id: post.id, locale: target_locale)
localization.raw = translated_raw
localization.cooked = post.post_analyzer.cook(translated_raw, post.cooking_options || {})
localization.post_version = post.version
localization.localizer_user_id = Discourse::SYSTEM_USER_ID
localization.save!
cooked_processor = LocalizedCookedPostProcessor.new(localization, post, {})
begin
cooked_processor.post_process
localization.update!(cooked: cooked_processor.html)
rescue => e
# Log but don't fail translation if post-processing (oneboxes, images) fails
Rails.logger.warn(
"Post-processing failed for localization of post #{post.id} to #{target_locale}: #{e.class} - #{e.message}",
)
end
localization
end
def self.model_name
"post"
end
end
end
end